Xcode7更新后,苹果不建议使用以前的AlertView和ActionSheet了,而是将二者合一,创建了一个新的视图控制器UIAlertViewController,UIAlertViewController继承自UIViewController,通过改变设置不同的UIAlertControllerStyle来确定显示的是AlertView或者是ActionSheet.通过添加AlertAction来增加按钮,话不多说,贴上自己写的一个小Demo.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self CreateUI];
}
- (void)CreateUI
{
UIButton * button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setFrame:CGRectMake(100, 100, 100, 50)];
[button1 setTitle:@"ActionSheet" forState:UIControlStateNormal];
button1.backgroundColor = [UIColor blackColor];
[button1 addTarget:self action:@selector(ShowActionSheet) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setFrame:CGRectMake(100, 180, 100, 50)];
[button2 setTitle:@"AlertView" forState:UIControlStateNormal];
button2.backgroundColor = [UIColor blackColor];
[button2 addTarget:self action:@selector(ShowAlertView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
}
- (void)prepareAlertCWithStyle:(UIAlertControllerStyle)alertstyle
{
UIAlertController *_alertC = [UIAlertController alertControllerWithTitle:@"这是AlertController的测试" message:@"iOS8以后用UIAlertController" preferredStyle:alertstyle];
// 添加取消按钮UIAlertActionStyleCancel
UIAlertAction *canleaction = [UIAlertAction actionWithTitle:@"取消按钮" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(@"点击了取消按钮");
}];
[_alertC addAction:canleaction];
// 添加普通按钮UIAlertActionStyleDefault
UIAlertAction *defaultaction = [UIAlertAction actionWithTitle:@"普通按钮" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(@"点击了普通按钮");
}];
[_alertC addAction:defaultaction];
// 添加文本框,只能在alertview模式下添加textfiled
if (alertstyle == UIAlertControllerStyleAlert) {
[_alertC addTextFieldWithConfigurationHandler:^(UITextField *textField) {
// 这里可以对文本框进行一些自定义操作
textField.placeholder = @"请输入.....";
}];
}
// 添加UIAlertActionStyleDestructive样式按钮
UIAlertAction *replaceaction = [UIAlertAction actionWithTitle:@"销毁按钮" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {
if (alertstyle == UIAlertControllerStyleAlert) {
NSLog(@"%@",_alertC.textFields[0].text);
}
NSLog(@"点击了销毁样式按钮");
}];
[_alertC addAction:replaceaction];
// 显示alertview,UIAlertController是继承与UIViewController的
[self presentViewController:_alertC animated:YES completion:nil];
}
- (void)ShowActionSheet
{
// 设置为ActionSheet样式
[self prepareAlertCWithStyle:UIAlertControllerStyleActionSheet];
}
- (void)ShowAlertView
{
// 设置为AlertView样式
[self prepareAlertCWithStyle:UIAlertControllerStyleAlert];
}