我有一个场景,可能需要重命名某些内容,我想用它UIAlertController
来收集新名称。我希望它能够同时进行几次更改(虽然不太可能,但我想支持它)。
问题是我只需要在当前的结果出现时循环才能继续UIAlertController
,事实上,循环会立即继续,当然一次不能出现多个。我一整天都被困在这个问题上,需要帮助。
我需要某种使用完成处理程序为下一个循环迭代提供绿灯的方法。
这是问题的简化版本,changeNames 函数位于UIViewController
.
var names = ["Bob","Kate"]
func changeNames(){
for name in names {
let alert = UIAlertController(title: "Rename \(name)",
message: "What would you like to call \(name)?",
preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
textField.text = name
})
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
print("User changed \(name) to \(alert!.textFields![0].text)")
//Don't continue the loop until now
}))
self.present(alert, animated: true)
}
}
谢谢
异步代码很难循环,我宁愿使用递归:
func showChangeAlerts(for texts: [String]) {
guard let value = texts.first else { return }
let alert = UIAlertController(title: "Rename \(value)",
message: "What would you like to call \(value)?",
preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField
textField.text = value
})
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert, weak self] (_) in
let newValue = alert?.textFields![0].text ?? ""
print("User changed \(value) to \(newValue)")
self?.showChangeAlerts(for: Array(texts.dropFirst()))
}))
self.present(alert, animated: true)
}
您传入一个字符串数组,此方法将处理它们,直到处理完所有字符串。
编辑
好的,刚刚看到 Ron Nabuurs 用一个非常相似的解决方案击败了我 :) 主要区别在于我的方法不使用额外的迭代器参数,而是从提供的数组中“消耗”字符串直到它为空。但原理是一样的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句