你在这里有多种可能性。
您可以使用find
得到UIAlertAction
index
find
让您找到数组中对象的索引。你可以用它来find
的索引action
(作为参数传递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
here).
该解决方案的真正优点在于您可以捕获任何内容。您甚至可以捕获一个假设Doctor
代表您的医生的对象,或者直接是医生 ID 等!
使用循环
但通常你会使用添加你的动作for
循环,那么为什么不利用这一点,再加上闭包以及它们捕获变量的事实,来制作一个很好的函数,直接告诉您所选医生的 ID?
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) {}
}