我想创建以下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是用title、message初始化的,以及它是更喜欢显示为警报还是操作表。
当按钮被按下时,我想显示警报,但是alert.show()不工作。为什么我的代码不能工作?
发布于 2015-01-25 22:46:34
这里的主要问题是,UIAlertController (与UIAlertView不同)是UIViewControlller的子类,这意味着它需要这样表示(而不是通过show()方法)。除此之外,如果您想要将cancel按钮的颜色更改为红色,则必须将cancel操作的警告样式设置为.Destructive。
仅当您希望按钮为红色时,此选项才有效。如果要将警报控制器中按钮的颜色更改为任意颜色,只能通过在警报控制器的view属性上设置tintColor属性来实现,这将更改其所有按钮的色调颜色(破坏性按钮除外)。需要注意的是,根据苹果的设计模式,取消按钮的颜色没有必要改变,因为它有粗体文本的含义。
但是,如果您仍然希望文本是红色的,可以这样做:
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)它会产生你想要的结果:

发布于 2015-01-25 22:30:54
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) {
// ...
}发布于 2015-01-25 22:29:56
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“实际显示您的警报。
希望它能正常工作;)
https://stackoverflow.com/questions/28137259
复制相似问题