【发布时间】:2017-05-11 16:11:49
【问题描述】:
我有一个 UIAlertViewController 的简单用法,其中我将按钮标签和操作函数作为参数传递给名为 showAlert() 的函数,该函数设置并调用警报。我在 in 闭包的 UIAlertAction 中有操作函数。
异常行为:当 showAlert 被执行而不是按钮被按下时,action 函数就会被执行。
另一个问题是当按下按钮时警报会自动消失。我没有解雇声明。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func test1() {
NSLog("test 1 executed")
}
@IBAction func show(_ sender: UIButton) {
self.showAlert(title: "Title", message: "Message",titleString: "A,B,C", function:test1())
}
func showAlert(title: String, message: String, titleString: String, function: ()) {
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let labels = titleString.components(separatedBy: ",")
var actions = [UIAlertAction()]
for label in labels {
let a = UIAlertAction(title: label, style: .default) { action in
function // executed as soon as showAlert is called!!
// Expecting to be called when button is pressed
NSLog("\(label) Pressed")
}
actions.append(a)
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in
NSLog("Cancel Button pressed.")
}
for action in actions {
alertController.addAction(action)
}
// Add the actions.
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
控制台上的响应是: 2017-05-11 11:55:15.593 AlertTest[5304:8818290] 函数执行 2017-05-11 11:55:25.287 AlertTest[5304:8818290] 按下
【问题讨论】: