在 Swift 中创建一个 UIAlertAction

Create an UIAlertAction in Swift

我想创建以下 UIAlertAction:

@IBAction func buttonUpgrade(sender: AnyObject) {

           let alertController = UIAlertController(title: "Title",
        message: "Message",
        preferredStyle: UIAlertControllerStyle.Alert)

    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
        // ...
    }

    alertController.addAction(cancelAction)
}

我知道 UIAlertController 是用 titlemessage 初始化的,并且它更喜欢显示为警报还是操作 sheet。

按下按钮时我想显示警报,但 alert.show() 不起作用。为什么我的代码不起作用?

var alertController = UIAlertController(title: "Alert", message:"Message", preferredStyle: UIAlertControllerStyle.Alert)
let confirmed = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

alertController.addAction(confirmed)
alertController.addAction(cancel)
self.presentViewController(alertController, animated: true, completion: nil)

重要的是最后一行 "self.presentViewController" 实际显示您的警报。

希望有用 ;)

let alertController = UIAlertController(
    title: "Title",
    message: "Message",
    preferredStyle: UIAlertControllerStyle.Alert
)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
    // ...
}

let okayAction = UIAlertAction(title: "OK", style: .Default) { (action) in
    // ...
}

alertController.addAction(okayAction)    
alertController.addAction(cancelAction)

self.presentViewController(alertController, animated: true) {
    // ...
}

这里的主要问题是 UIAlertController(不像 UIAlertView)是 UIViewControlller 的子类,这意味着它需要这样显示(而不是通过 show() 方法)。除此之外,如果要将取消按钮的颜色更改为红色,则必须将取消操作的警报样式设置为 .Destructive

这仅在您希望按钮为红色时有效。如果要将警报控制器中的按钮颜色更改为任意颜色,只能通过在警报控制器的 view 属性 上设置 tintColor 属性 来完成,这将更改其所有按钮的色调(破坏性按钮除外)。应该注意的是,根据 Apple 已经实施的设计范例,没有必要更改取消按钮的颜色,因为它具有粗体文本的含义。

如果您仍然希望文本为红色,可以这样做:

let alertController = UIAlertController(
    title: "Title",
    message: "Message",
    preferredStyle: UIAlertControllerStyle.Alert
)

let cancelAction = UIAlertAction(
    title: "Cancel",
    style: UIAlertActionStyle.Destructive) { (action) in
    // ...
}

let confirmAction = UIAlertAction(
    title: "OK", style: UIAlertActionStyle.Default) { (action) in
    // ...
}

alertController.addAction(confirmAction)
alertController.addAction(cancelAction)

presentViewController(alertController, animated: true, completion: nil)

这会产生您想要的结果: