我知道这是一个非常简单的问题,我从3小时开始研究它,但却无法使其正常工作。我正在尝试使用Apple documentation来实现UIAlertController以显示错误消息,但我在这一行上收到错误,没有已知的选择器presentViewController [self presentViewController:alert animated:YES completion:nil];
类方法我搜索并获得了许多解决方案,但没有在这里工作。 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
答案 0 :(得分:7)
为什么showAlert:method 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];