[英]UIAlertView delegate method clickedButtonAtIndex: is not working
我有一个类MyClass
,我想将其设置为UIAlertView的委托。 我的代码是
@interface MyClass : NSObject <UIAlertViewDelegate>
@end
@implementation MyClass
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSLog(@"Clicked button at Index 1");
}
else {
NSLog(@"Whatever");
}
}
@end
并在ViewController.m中
#import "MyClass"
@interface ViewController() {
}
@end
static MyClass *mc;
@implementation ViewController
-(void)viewDidLoad {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:mc cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", @"nice"];
[alert show];
}
@end
当我运行该应用程序时,会出现警报,但是当我单击索引1或任何其他按钮时,什么也没有发生。 那么如何解决这个问题。
谢谢。
您需要实际分配/初始化mc
诸如此类的东西(不要忘了称其为super):
-(void)viewDidLoad {
[super viewDidLoad];
if (mc == nil)
mc = [MyClass alloc] init];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:mc cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", @"nice"];
[alert show];
}
您正在将委托设置为一个未初始化的对象。 确保mc
不为nil,如果是,则在创建警报之前添加alloc / init行以创建mc
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.