我知道这是一个非常简单的问题,我已经研究了 3 个小时,但没能成功。我正在尝试实现 UIAlertController 以使用 Apple documentation 显示错误消息,但我在这一行上收到错误,选择器 presentViewController 没有已知的类方法AlertMessageViewController 是我自定义的类,继承自 UIViewController。
AlertMessageViewController.h
#import <UIKit/UIKit.h>
@interface AlertMessageViewController : UIViewController
+(instancetype)showAlert: (NSString *) title withMessage: (NSString*) message preferredStyle:(UIAlertControllerStyle)preferredStyle;
@end
AlertMessageViewController.m
#import "AlertMessageViewController.h"
#import <UIKit/UIKit.h>
@interface AlertMessageViewController ()
@end
@implementation AlertMessageViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
+(instancetype)showAlert: (NSString *) title withMessage: (NSString*) message preferredStyle:(UIAlertControllerStyle)preferredStyle
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"alertMessage" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok =[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){NSLog(@"ok action");}];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
@end
最佳答案
为什么你的showAlert:方法的返回类型是instancetype?而且你没有返回任何东西,它应该是无效的。
编辑:此外,您的方法不应该是类方法
这应该有效:
-(void)showAlert: (NSString *) title withMessage: (NSString*) message preferredStyle:(UIAlertControllerStyle)preferredStyle
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"alertMessage" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok =[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){NSLog(@"ok action");}];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
更新: 好的试试这个:
+(UIAlertController*)alertWithTitle: (NSString *) title withMessage: (NSString*) message preferredStyle:(UIAlertControllerStyle)preferredStyle
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle: preferredStyle];
UIAlertAction *ok =[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){NSLog(@"ok action");}];
[alert addAction:ok];
return alert;
}
}
然后当你想展示它的时候,这样调用它:
[self presentViewController:[AlertMessageViewController alertWithTitle:@"Title" withMessage:@"Message" preferredStyle:UIAlertControllerStyleAlert] animated:YES completion:NULL];
关于objective-c - UIAlertController 中的选择器 presentViewController 没有已知的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31292293/