使用UIAlertControllerStyle.ActionSheet在UIAlertController中取消按钮

18 xcode ios swift uialertcontroller uialertaction

我想在我的UIAlert中添加一个单独的取消按钮.

我知道如何使用UIActionSheet,但UIAlert也应该可以,对吗?

var sheet: UIActionSheet = UIActionSheet();
    let title: String = "...";
    sheet.title  = title;
    sheet.delegate = self;
    sheet.addButtonWithTitle("Cancel");
    sheet.addButtonWithTitle("...")
    sheet.cancelButtonIndex = 0;
    sheet.showInView(self.view);
Run Code Online (Sandbox Code Playgroud)

这将有一个...按钮和一个分开的取消按钮.

所以有人知道如何做到这一点

    var alert = UIAlertController(title: "...", message: "....", preferredStyle: UIAlertControllerStyle.ActionSheet)
Run Code Online (Sandbox Code Playgroud)

我是xcode和swift的新手很抱歉,如果这个问题是愚蠢或任何事情......

Jac*_*ley 46

它非常简单,但与以前的工作方式有点不同.现在,您可以为警报添加"操作".然后,这些操作由设备上的按钮表示.

alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
Run Code Online (Sandbox Code Playgroud)

以上是简单取消按钮所需的代码 - 请记住,警报的解除是自动完成的,所以不要把它放在你的处理程序中.如果您想创建另一个执行某些操作的按钮,请使用以下代码:

alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.Default, handler: { action in
        println("This button now calls anything inside here!")
    }))
Run Code Online (Sandbox Code Playgroud)

希望我理解你的问题,这就回答了你的要求.我还要补充一点,添加完所有"操作"后,使用以下代码显示警报:

self.presentViewController(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


小智 7

我想继续为特定问题提供具体答案.用户询问"取消"按钮的实现,而不是默认按钮.看看下面的答案!

let alertController = UIAlertController(title: "Select one", message: "Hey! Press a button", preferredStyle: .actionSheet)

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

alertController.addAction(cancelAction)

self.present(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)