UIAlertController基本使用和循环引用问题
UIAlertController是苹果在iOS8里新推出的一个玩意。它把之前我们用来现实提示框的UIAlertView和UIAlertAction集成在一起了,而且不论在iPhone还是iPad上都能统一使用啦。
从UIAlertController的定义可以发现
NS_CLASS_AVAILABLE_IOS(8_0) @interface UIAlertController : UIViewController
它是一个UIViewControll,就是说你面前的这个在屏幕中间或是屏幕下方显示的小窗口是一个控制器了,不在是一个UIView。一段简洁的代码来说明它的基本使用
1 UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"new alert" message:@"this is a alert viewController" preferredStyle:UIAlertControllerStyleAlert]; 2 3 4 [alert addAction:[UIAlertAction actionWithTitle:@"submit" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { 5 NSLog(@"click submit button"); 6 7 NSLog(@"first textField's text is %@,the second textField's text is %@",[alert.textFields.firstObject text],[alert.textFields.lastObject text]); 8 }]]; 9 [alert addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { 10 NSLog(@"click cancel button"); 11 }]]; 12 [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { 13 14 textField.textColor=[UIColor orangeColor]; 15 }]; 16 [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { 17 textField.secureTextEntry=YES; 18 }]; 19 20 //现实控制器 首先想到的是modal presentViewController方法 21 [self presentViewController:alert animated:YES completion:nil];
使用特点:
1、通过preferredStyle来确定显示风格,它有两个选择
UIAlertControllerStyleActionSheet = 0,
UIAlertControllerStyleAlert
2、通过addAction来添加按钮,这个方法提供block来实现按钮点击的具体行为,各个按钮的处理分开,互补干扰
3、通过addTextFieldWithConfigurationHandler来添加文本框,在这个方法的block里可以*设置文本框的一些样式,更加方便
4、因为UIAlertController是控制器,控制器的显示首先想到的是用presentViewController方法
打印内容如下
2015-03-16 17:31:30.479 iOS8NewFeature[4247:152311] click submit button
2015-03-16 17:31:30.480 iOS8NewFeature[4247:152311] first textField's text is luseike,the second textField's text is 123
————————————————————————————————————————————————————————————————————————
在打印出文本框内容的block内,看上去貌似有些循环引用的感觉,alert身上有个action的block,block内部又引用着alert,为了弄清楚是UIAlertController没有释放还是我们的代码有问题,可以自定义一个继承于UIAlertController的类,实现其dealloc方法来看一下
#import "MyViewController.h" @interface MyViewController () @end @implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; } -(void)dealloc{ NSLog(@"MyViewController--dealloc"); }