这里有多种可能性。
您可以使用find 获取UIAlertAction 索引
find 让您在数组中找到对象的索引。你可以用它来findaction的索引(即作为UIAlertAction的处理程序的参数传递,即UIAlertAction本身)在所有操作的alert.actions数组中。
let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
let closure = { (action: UIAlertAction!) -> Void in
let index = find(alert.actions as! [UIAlertAction], action)
println("Index: \(index)")
}
alert.addAction(UIAlertAction(title: "Doc1", style: .Default, handler: closure))
alert.addAction(UIAlertAction(title: "Doc2", style: .Default, handler: closure))
alert.addAction(UIAlertAction(title: "Doc3", style: .Default, handler: closure))
alert.addAction(UIAlertAction(title: "Doc4", style: .Default, handler: closure))
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
println("User cancelled.")
})
self.presentViewController(alert, animated: true) {}
你可以创建一个闭包……返回一个闭包
创建一个带有您选择的参数的闭包(此处为Int)并返回一个捕获该参数的闭包,以便您可以使用它
let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
let closure = { (index: Int) in
{ (action: UIAlertAction!) -> Void in
println("Index: \(index)")
}
}
alert.addAction(UIAlertAction(title: "Doc1", style: .Default, handler: closure(0)))
alert.addAction(UIAlertAction(title: "Doc2", style: .Default, handler: closure(1)))
alert.addAction(UIAlertAction(title: "Doc3", style: .Default, handler: closure(2)))
alert.addAction(UIAlertAction(title: "Doc4", style: .Default, handler: closure(3)))
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in
println("User cancelled.")
})
self.presentViewController(alert, animated: true) {}
这样你就有了一个函数(闭包),它为你的UIAlertAction 处理程序生成闭包,除了它们捕获不同的对象(这里是不同的Int)之外,它们都具有相同的主体。
此解决方案的真正优点在于您可以捕获任何内容。您甚至可以捕获代表您的医生的假设 Doctor 对象,或者直接捕获医生 ID 等!
使用循环
但通常你会使用for 循环添加你的动作,所以为什么不利用它,加上利用闭包和它们捕获变量的事实,来制作一个很好的函数,直接告诉你选择医生的身份证?
func testMyAlert() {
let doctors = [
["Name": "Doctor for Disease AAA", "Doctor_id": "21"],
["Name": "Doctor for Disease BBB", "Doctor_id": "22"],
["Name": "Doctor for Disease AAA", "Doctor_id": "25"]
]
chooseDoctor(doctors) { selectedDocID in
if let docID = selectedDocID {
println("User selected doctor with ID \(docID)")
} else {
println("User cancelled, no doctor selected")
}
}
}
func chooseDoctor(doctors: Array<[String:String]>, completion: Int?->Void) {
let alert = UIAlertController(title: "Doctors", message: "Choose a doctor", preferredStyle: .ActionSheet)
for doc in doctors {
let action = UIAlertAction(title: doc["Name"]!, style: UIAlertActionStyle.Default) { _ in
// On selecting this action, get the doctor's ID, convert it to an Int, and return that.
completion(doc["Doctor_id"]?.toInt())
}
alert.addAction(action)
}
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { _ in completion(nil) } )
self.presentViewController(alert, animated: true) {}
}