在iOS8中UIAlertController已經取代UIActionsheet UIAlertView。
可以創建一個AlertController“標題”和“消息”來作為警告框。UIAlertController的兩種設置格式:
- UIAlertControllerStyleActionSheet
用于配置UIAlertController ActionSheet - UIAlertControllerStyleAlert
用于配置UIAlertController警報。
1.創建一個alert對象和一個actionsheet對象,請看以下code:
- 創建AlertController對象:
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"title"
message:@"Select a title"
preferredStyle:UIAlertControllerStyleAlert];
- 添加action:
[alertView addAction:[UIAlertAction actionWithTitle:@"ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
//要做的事情
}]];
在你點擊‘ok’的時候會回調handler這個block
- 顯示alertController
[self presentViewController:alertView animated:YES completion:{
BJLog("show the alertView");
}];
2.創建一個簡單的提醒OK按鈕和消息
下面的這個方法將創建一個簡單的AlertController在iOS8警報
- (void)showAlertView
{
//創建alertcontroller對象
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"simple" message:@"This is an simple AlertView" perferredStyle:UIAlertControllerAlert];
//添加action
[alertView addAction:[UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { //要做的事情
BJLog(@"action - %@", action.title);
}]];
//顯示alertView
[self presentViewController:alertView animated:YES completion:^{
NSLog(@"alertView shown!");
}];
}
3.創建一個警告文本框:
- (void)showAlertWithTextField {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"Menu"
message:@"Select a menu"
preferredStyle:UIAlertControllerStyleAlert];
[alertView addTextFieldWithConfigurationHandler:^(UITextField *textField) {
//Customize the textField
textField.placeholder = @"User name";
textField.textColor = [UIColor whiteColor];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.backgroundColor = [UIColor colorWithRed:171/255 green:182/255 blue:255/255 alpha:0.5];
}];
[alertView addAction:[UIAlertAction actionWithTitle:@"ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
BJLog(@"action - %@", action.title);//callback
}]];
[self presentViewController:alertView animated:YES completion:^{
BJLog(@"completed");
}];
}
4.給AlertController添加兩個文本框:
- (void)showActionSheetWithTwoButtons {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"ActionSheet!"
message:@"This is an ActionSheet."
preferredStyle:UIAlertControllerStyleActionSheet];
[alertView addAction:[UIAlertAction actionWithTitle:@"ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSLog(@"action - %@", action.title);
}]];
[alertView addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSLog(@"action - %@", action.title);
}]];
[self presentViewController:alertView animated:YES completion:^{
NSLog(@"alertView shown!");
}];
}
代碼比較簡單,就不讓代碼君出來玩了!