UIAlertView wont delegate

拈花ヽ惹草 提交于 2019-12-12 03:16:21

问题


I'm try to get from an UIAlertView the Content with following:

UIAlertView *loginView = [[UIAlertView alloc] initWithTitle:@"Login"
                                                    message:@"Please enter user and pass"
                                                   delegate:self
                                          cancelButtonTitle:@"Abort"
                                          otherButtonTitles:@"Login", nil];
[loginView setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[loginView show];

and then

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        UITextField *username = [alertView textFieldAtIndex:0];
        NSLog(@"username: %@", username.text);

        UITextField *password = [alertView textFieldAtIndex:1];
        NSLog(@"password: %@", password.text);

    }
}

in my .h File

@interface loginTest :  UIViewController <UIAlertViewDelegate>

what is wrong here?


回答1:


I think your question is missing some important details that are causing the issue, so answer comes from speculating on the last comment you made. You need to have all your view controllers implement the alert view delegate that will be presenting a UIAlertView. It sounds like you implement the delegate in ViewController, but not in abc. To further explain, here's an explanation in code.

Lets say you have ViewControllerA and ViewControllerB. In ViewControllerA.h:

@interface ViewControllerA : UIViewController <UIAlertViewDelegate>

And in ViewControllerB.h:

@interface ViewControllerB : UIViewController <UIAlertViewDelegate> 

Then in both ViewControllerA.m and ViewControllerB.m, you need to implement:

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        // do stuff
    }
}

When you display a UIAlertView and set the delegate to self, self refers to the view controller that you are currently in. If only one of your view controllers implement the delegate methods, and a different view controller displays the alert, the alert reports back to the view controller that presented it (which doesn't implement the delegate), therefore it doesn't do anything when it's done. I hope this answers your question.



来源:https://stackoverflow.com/questions/27965885/uialertview-wont-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!