蘋果不斷的推出一些新的方法去代替老的方法,而推出這些方法的主要思想就是"統一",也可以理解為把一些相似的功能整合到一個控件或者方法里面,下面要說的就是UIAlertController
.
/
在iOS8 之后推出的UIAlertController
其實就是對iOS8之前所用的兩個控件UIActionSheet
和UIAlertView
的整合,打開Xcode你會發現iOS8之后這兩個方法都被棄用了,因為UIAlertController
擁有了兩個控件的所有功能.
下面就是代碼測試
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 危險操作:彈框提醒
// iOS8 開始:UIAlertController 包含以上兩個的功能
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"你有嚴重的病癥" preferredStyle:UIAlertControllerStyleAlert];
// 添加按鈕
__weak typeof (alert)temp = alert; // 防止block循環引用,導致alert控制器無法自動銷毀
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 獲取文字
NSString *text = [temp.textFields.firstObject text];
NSString *text1 = [temp.textFields.lastObject text];
NSLog(@"你想做的事情,第一個文本框的文字是: %@,第二個文本框的文字是: %@",text,text1);
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"其他" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
/*
UIAlertActionStyleDefault = 0, // 默認
UIAlertActionStyleCancel, // 取消類
UIAlertActionStyleDestructive // 銷毀性的按鈕
*/
// 添加文本框(只能在UIAlertControllerStyleAlert添加文本框)
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
// 可以通過設置textField的屬性達到相應的效果
textField.textColor = [UIColor redColor];
// 監聽文字改變
// 以通知的方式監聽文字改變的話要在點擊確定|取消按鈕的時候銷毀通知,認不是用dealloc
// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userChange:) name:UITextFieldTextDidChangeNotification object:textField];
// UITextField 繼承自UIControl
[textField addTarget:self action:@selector(userChange:) forControlEvents:UIControlEventEditingChanged];
}];
/*
// 通過以下屬性可以看出,我們可以監聽鍵盤彈出,和鍵盤隱藏
UIControlEventEditingDidBegin // 開始編輯
UIControlEventEditingChanged // 正在編輯
UIControlEventEditingDidEnd // 結束編輯
UIControlEventEditingDidEndOnExit // 退出編輯
*/
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.secureTextEntry = YES;
}];
// 因為是控制器類型,所以:
[self presentViewController:alert animated:YES completion:nil];
}
// 這樣既可以監聽文字的改變,又可以獲取到改變的文字
- (void)userChange:(UITextField *)name
{
NSLog(@"%@",name);
}
B9E2172A-010F-4E0E-B9D5-F86364E58D1C.png