首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift中创建UIAlertAction

在Swift中创建UIAlertAction
EN

Stack Overflow用户
提问于 2015-01-25 22:04:41
回答 3查看 24.1K关注 0票数 5

我想创建以下UIAlertAction

代码语言:javascript
复制
@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初始化的,以及它是更喜欢显示为警报还是操作表。

当按钮被按下时,我想显示警报,但是alert.show()不工作。为什么我的代码不能工作?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-01-25 22:46:34

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

仅当您希望按钮为红色时,此选项才有效。如果要将警报控制器中按钮的颜色更改为任意颜色,只能通过在警报控制器的view属性上设置tintColor属性来实现,这将更改其所有按钮的色调颜色(破坏性按钮除外)。需要注意的是,根据苹果的设计模式,取消按钮的颜色没有必要改变,因为它有粗体文本的含义。

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

代码语言:javascript
复制
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)

它会产生你想要的结果:

票数 16
EN

Stack Overflow用户

发布于 2015-01-25 22:30:54

代码语言:javascript
复制
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) {
    // ...
}
票数 5
EN

Stack Overflow用户

发布于 2015-01-25 22:29:56

代码语言:javascript
复制
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“实际显示您的警报。

希望它能正常工作;)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28137259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档