返回在UIAlertView上按下按钮的结果给c++方法

Returning result of button pressed on UIAlertView to C++ method

本文关键字:结果 c++ 方法 按钮 UIAlertView 返回      更新时间:2023-10-16

我需要调用一个UIAlertView从一个c++文件显示。根据按下的按钮,我需要向c++类本身返回一个bool值(该bool值反过来被返回并在其他地方使用)。我想要一些关于如何将结果返回到c++类的建议。我已经假定我们不能将c++类设置为UIAlertView的委托,所以我需要以某种方式将哪个按钮按回c++类。

这是来自c++的函数调用示例(它是一个c++类,但编译为Objective-C:

bool CPlatform::WarningMessage(const wchar_t* message)
{
    // Some functions to convert message to an NSString* wNSString
    MessagePopUp *message = [[MessagePopUp alloc] init];
    [message showPopUpWithMessage:wNSString];
    // This function should return true if OK is pressed, or False if Cancel is pressed.
}
然后,我有一个简单的类来显示警报
@interface MessagePopUp : NSObject <UIAlertViewDelegate> {
BOOL OKPressed;
}
- (void) showPopUpWithMessage:(NSString*)message;
@end
@implementation MessagePopUp
- (void) showPopUpWithMessage:(NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)
    {
        NSLog(@"ok");
        OKPressed = true;
    }
    else
    {
        NSLog(@"cancel");
        OKPressed = false;
    }
}
@end

你能推荐一种方法,我可以返回结果/OKPressed到c++函数?

谢谢

考虑代码流程会告诉您,这不是那么容易做到的。

问题是运行循环和UIAlertView是非阻塞显示alertView(即调用[alert show]后),你需要返回控制到iOS,这意味着你的c++函数bool CPlatform::WarningMessage(const wchar_t* message)必须返回之前,你知道哪个按钮被按下。

你可以尝试建立一个阻塞UIAlertView,但这不是一个好主意,即使这种类型的事情是可能的。

一个更好的主意是在你的c++ CPlatform类中定义一个回调,它接受你在clickedButtonAtIndex委托方法中的OKPressed bool值。

如果你可以混合这两种语言,那么你可以使用objective-c中一个叫做NSNotificationCenter的概念。

下面的代码为"show the alert"类的父类添加了一个监听器:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(MethodYouWantToUseWhenClicked) 
                                             name:@"alertViewClicked" 
                                           object:showAlertClass];

然后在alert视图类中,您可以执行以下操作来发送消息:

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)
    {
        // Not sure, but I think buttonIndex == 0 is actually cancel.
        NSLog(@"cancel");
        self.OKPressed = false;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"alertViewClicked" 
                                                            object:self];
    } else {
        self.OKPressed = false;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"alertViewClicked" 
                                                            object:self];
    }
}

那么你只需要从你的父类/c++中访问布尔属性。