Objective c UIAlertView不会委派

Objective c UIAlertView不会委派,objective-c,cocoa-touch,uikit,Objective C,Cocoa Touch,Uikit,我正在尝试从UIAlertView获取以下内容: UIAlertView *loginView = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Please enter user and pass" delegate:self

我正在尝试从UIAlertView获取以下内容:

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

-(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);

    }
}
在我的.h文件中

@interface loginTest :  UIViewController <UIAlertViewDelegate>
@接口登录测试:UIViewController

这里怎么了

我认为你的问题遗漏了一些导致问题的重要细节,所以答案来自于对你上一次评论的猜测。您需要让所有视图控制器实现警报视图委托,该委托将显示
UIAlertView
。听起来像是在
ViewController
中实现委托,而不是在
abc
中实现委托。为了进一步解释,这里有一个代码解释

假设您有
ViewControllerA
ViewControllerB
。在
ViewControllerA.h
中:

@interface ViewControllerA : UIViewController <UIAlertViewDelegate>
@interface ViewControllerB : UIViewController <UIAlertViewDelegate> 
然后在
ViewControllerA.m
ViewControllerB.m
中,您需要实现:

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

当您显示
UIAlertView
并将代理设置为
self
时,
self
表示您当前所在的视图控制器。如果只有一个视图控制器实现了委托方法,而另一个视图控制器显示了该警报,则该警报会向显示它的视图控制器报告(该视图控制器不实现委托),因此完成后它不会执行任何操作。我希望这能回答你的问题

什么不起作用?我无法从文本字段中获取值。您的委托方法是否触发?您是否按下了正确的按钮(索引==1)?不,如果(buttionIndex==1)伪代码很好,但objc喜欢非常描述性的类和变量名,则在之前手动测试并添加了NSLog:)类也总是大写的。想想你未来的编码同事,他们将阅读this@mucmun太好了,很高兴我能帮忙:)