1、基本使用網絡
使用UIAlertController 需三步:指針
1.建立控制器並指定樣式和參數.。code
2.添加按鈕addAction。server
3.模態推出(底部或中間彈出)。rem
// 1. 建立alert控制器並指定style:UIAlertControllerStyleAlert||UIAlertControllerStyleActionSheet 本文以 Alert爲例展現 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"肯定要操做?" message:@"操做後不可恢復" preferredStyle:UIAlertControllerStyleAlert]; // 2. 添加選項 [alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"點擊了取消"); }]]; [alertController addAction: [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { NSLog(@"點擊了肯定"); }]]; // 3. 模態退出控制器 [self presentViewController:alertController animated:YES completion:nil];
*若是選項添加超過兩個,會豎向排列。it
2、(舉個栗子)可添加輸入框,可用做輸入密碼等功能,也可添加多個輸入框(如用戶名和密碼)。io
效果圖:
*要對輸入框中的文字進行監測,密碼超過6位肯定按鈕纔可點。變量
由於要對AlertController的成員進行監聽,而且操做肯定按鈕,因此提兩個全局變量。object
UIAlertAction * _otherAction; //肯定按鈕 UIAlertController * _alertController; // 控制器
-(void)buttonClinck{select
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"輸入密碼" message:@"密碼爲開機密碼" preferredStyle:UIAlertControllerStyleAlert]; _alertController = alertController; [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { textField.secureTextEntry = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
}]; __weak actionsheetController *Wself = self; //blcok中使用self最好用copy弱指針self,雖然有些block是局部變量(self並不包含block),但爲保險,告誡本身都用。 [alertController addAction: [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { [Wself remoteNotif]; }]]; UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [Wself remoteNotif]; }]; [alertController addAction: otherAction]; otherAction.enabled = NO; _otherAction = otherAction; //先將肯定按鈕設爲不可點,在通知中當輸入的密碼大於n位數能夠點 //推出控制器 [self presentViewController:alertController animated:YES completion:nil];
}
-(void)remoteNotif{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:_alertController.textFields.firstObject];
}
-(void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification{
UITextField *textFile = notification.object; _otherAction.enabled = textFile.text.length>5?YES:NO;
}
至此完結,注意添加監聽後要移除。
文章借鑑網絡,怕忘了本身總結的。不對的地方,請提出。