使用 UIAlertController 的动作表

使用 UIAlertController,使用与用于 AlertViews 相同的 API 创建与已弃用的 UIActionSheet 相同的操作表。

带两个按钮的简单操作表

迅速

 placeholderCopylet alertController = UIAlertController(title: "Demo", message: "A demo with two buttons", preferredStyle: UIAlertControllerStyle.actionSheet)

Objective-C

 placeholderCopyUIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Demo" message:@"A demo with two buttons" preferredStyle:UIAlertControllerStyleActionSheet];

创建按钮取消

迅速

 placeholderCopylet cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (result : UIAlertAction) -> Void in
    //action when pressed button
}
let okAction = UIAlertAction(title: "Okay", style: .default) { (result : UIAlertAction) -> Void in
    //action when pressed button
}

Objective-C

 placeholderCopyUIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        //action when pressed button
    }];

UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //action when pressed button
    }];

并将它们添加到操作表:

迅速

 placeholderCopyalertController.addAction(cancelAction)
alertController.addAction(okAction)

Objective-C

 placeholderCopy[alertController addAction:cancelAction];
[alertController addAction:okAction];

现在介绍 UIAlertController

迅速

 placeholderCopyself.present(alertController, animated: true, completion: nil)

Objective-C

 placeholderCopy[self presentViewController:alertController animated: YES completion: nil];

这应该是结果:

StackOverflow 文档

带有破坏性按钮的操作表

使用 UIAlertActionStyle .destructive 作为 UIAlertAction 将创建一个红色调的按钮。

StackOverflow 文档

对于这个例子,上面的 okAction 被这个 UIAlertAction 取代:

迅速

 placeholderCopylet destructiveAction = UIAlertAction(title: "Delete", style: .destructive) { (result : UIAlertAction) -> Void in
    //action when pressed button
}

Objective-C

 placeholderCopyUIAlertAction * destructiveAction = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {
            //action when pressed button
        }];