在Swift中创建UIAlertAction

切萨雷

我想创建以下内容UIAlertAction

img1

@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)
}

我知道anUIAlertController是使用title初始化的message并且它是否更喜欢显示为警报或操作表。

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

米克麦卡勒姆

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

仅当您希望按钮为红色时才有效。如果要将警报控制器中按钮的颜色更改为任意颜色,则只能通过tintColor在警报控制器的view属性设置属性来完成,这将更改其所有按钮的色泽(破坏性按钮除外) )。应当指出,在苹果公司采用的设计范例中,由于其粗体文本的含义,因此不必更改取消按钮的颜色。

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

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)

产生您想要的结果:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章