我想建立一个UIAlertController
,有四个动作按钮,按钮的标题设置为"红心","黑桃","方块"one_answers"梅花"。当按钮被按下时,我想返回它的标题。
总之,这是我的计划:
// TODO: Create a new alert controller
for i in ["hearts", "spades", "diamonds", "clubs"] {
// TODO: Add action button to alert controller
// TODO: Set title of button to i
}
// TODO: return currentTitle() of action button that was clicked
试试这个:
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert)
for i in ["hearts", "spades", "diamonds", "hearts"] {
alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething)
}
self.presentViewController(alert, animated: true, completion: nil)
和处理动作在这里:
func doSomething(action: UIAlertAction) {
//Use action.title
}
为将来的参考,你应该看看苹果的文档ualertcontrollers
下面是一个示例代码,包含两个action +和ok-action:
import UIKit
// The UIAlertControllerStyle ActionSheet is used when there are more than one button.
@IBAction func moreActionsButtonPressed(sender: UIButton) {
let otherAlert = UIAlertController(title: "Multiple Actions", message: "The alert has more than one action which means more than one button.", preferredStyle: UIAlertControllerStyle.ActionSheet)
let printSomething = UIAlertAction(title: "Print", style: UIAlertActionStyle.Default) { _ in
print("We can run a block of code." )
}
let callFunction = UIAlertAction(title: "Call Function", style: UIAlertActionStyle.Destructive, handler: myHandler)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
// relate actions to controllers
otherAlert.addAction(printSomething)
otherAlert.addAction(callFunction)
otherAlert.addAction(dismiss)
presentViewController(otherAlert, animated: true, completion: nil)
}
func myHandler(alert: UIAlertAction){
print("You tapped: (alert.title)")
}}
与e.g. handler: myHandler定义一个函数,读取结果.
这只是一种方法;-)
有什么问题吗?