序言:UIAlertController在iOS8.0提出,目的是替换UIAlertView、UIActionSheet,这两个控件分别在9.0和8.3废弃。后两者是delegate响应选择按钮的点击事件,而UIAlertController是用block语法来实现。
今天我将的主题源于:UIAlertView、UIActionSheet继承自UIView,而UIAlertController是继承自UIViewController,所以当UIAlertController应用在UIView环境中(代码写在UI的子类中),则跟以前大大的不同。
UIAlertController弹出只能通过present,也就是说必须有控制器,这样才能present。
一个简单且实用的方法就是,新建一个UIViewController。
talk is cheap ,show you the code!
{
NSString * string;//这里为了说明定义的,无实际意义
UIViewController *viewCTL = [[UIViewController alloc]init];//临时UIViewController,从它这里present UIAlertController
[self addSubview:viewCTL.view];//这句话很重要,即把UIViewController的view添加到当前视图或者UIWindow
//以下为UIAlertController的构造和配置
UIAlertController *alertCTL = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
__weak typeof(alertCTL) kAlertCTL = alertCTL;
[alertCTL addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
[textField setSecureTextEntry:YES];
[textField setPlaceholder:string];
}];
[alertCTL addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
[textField setSecureTextEntry:YES];
[textField setPlaceholder:string];
}];
UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//处理点击取消按钮
[viewCTL.view removeFromSuperview];
}];
UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:string style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//处理点击确定按钮
[viewCTL.view removeFromSuperview];
}];
[alertCTL addAction:alertAction1];
[alertCTL addAction:alertAction2];
[viewCTL presentViewController:alertCTL animated:YES completion:nil];//弹出该UIAlertController
}
网友评论