但是在实际的工程开发中,我们有这样一个“潜规则”:要把每一个警告(warning)当做错误(error)。所以为了顺应苹果的潮流,我们来解决这个warning,使用UIAlertController来解决这个问题。代码如下:
#import "LoginViewController.h"
@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UIButton *login;
- (IBAction)loginOnClick:(UIButton *)sender;
@end
@implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
//获取通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//注册通知
[center addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.userName];
[center addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.passWord];
}
-(void)textChange
{
//当用户名框和密码框同时有内容时,登录按钮才可以点击
self.login.enabled = (self.userName.text.length > 0 && self.passWord.text.length > 0);
}
//点击登录按钮执行的事件
- (IBAction)loginOnClick:(UIButton *)sender {
if ([self.userName.text isEqual: @"xiaojin"] && [self.passWord.text isEqual: @"123456"]) {
NSLog(@"successful");
[self performSegueWithIdentifier:@"loginIdentifier" sender:nil];
} else {
//初始化提示框;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户名或密码出现错误" preferredStyle: UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//点击按钮的响应事件;
}]];
//弹出提示框;
[self presentViewController:alert animated:true completion:nil];
}
}
@end
看,这样就不会有警告了吧!编译运行后的界面和上面的一样。其中preferredStyle这个参数还有另一个选择:UIAlertControllerStyleActionSheet。选择这个枚举类型后,实现效果如下:












