使用 UIAlertController 的動作表

使用 UIAlertController,使用與用於 AlertViews 相同的 API 建立與已棄用的 UIActionSheet 相同的操作表。

帶兩個按鈕的簡單操作表

迅速

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

Objective-C

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

建立按鈕取消

迅速

let 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

UIAlertAction *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
    }];

並將它們新增到操作表:

迅速

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

Objective-C

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

現在介紹 UIAlertController

迅速

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

Objective-C

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

這應該是結果:

StackOverflow 文件

帶有破壞性按鈕的操作表

使用 UIAlertActionStyle .destructive 作為 UIAlertAction 將建立一個紅色調的按鈕。

StackOverflow 文件

對於這個例子,上面的 okAction 被這個 UIAlertAction 取代:

迅速

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

Objective-C

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