我的iOS应用程序(Swift 4,XCode 9)中有一个UITableView的子类。这个表有一行,我希望它在单击时显示一个警报,从用户获取一些输入,然后在用户单击警报中的"OK“时更新表中的标签(lblUserFromPrefs
)。目前一切正常,除了标签没有更新。下面是我的UITableView子类中的相关代码:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Clicked section: \(indexPath.section) row: \(indexPath.row)")
let alert = UIAlertController(title: "Username", message: "what is your name", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = ""
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert!.textFields![0]
if let text = textField.text {
print("Text field: \(text)")
DispatchQueue.main.async {
self.lblUserFromPrefs.text = text
print("label updated")
}
}
}))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
当我运行以下命令时,标签的文本不会在警报关闭时更改,而是在再次单击表行时立即更改。我不知道为什么它要等到该行再次被单击才能更新文本。所有的打印语句都会在我期望的时候打印(包括在按下警报的OK按钮时立即打印“标签更新”),并且它们会打印正确的内容。我知道当你试图从后台线程中的闭包更新UI时,你必须使用DispatchQueue.main.async {}
,但我不确定为什么它不更新,即使我使用的是主线程。我尝试过使用DispatchQueue.main.async(execute: {})
,并将self.lblUserFromPrefs.setNeedsDisplay()
直接放在self.lblUserFromPrefs.text = "text"
之后。你知道我做错了什么吗?谢谢!!
发布于 2019-06-05 06:51:37
将[weak self]
添加到派单,如下所示:
DispatchQueue.main.async { [weak self] in
}
发布于 2019-06-05 14:08:20
尝试如下所示:
let alertController = UIAlertController.init(title: "Enter some text", message: nil, preferredStyle: .alert)
alertController.addTextField { (textField) in
// Text field configuration
textField.placeholder = "Enter..."
textField.text = ""
}
alertController.addAction(UIAlertAction.init(title: "Ok", style: .default, handler: { (action) in
if (alertController.textFields?.first?.hasText)! {
if let text = alertController.textFields?.first?.text {
self.label.text = text // Update the value
}
} else {
self.label.text = "" // Default value
}
}))
self.present(alertController, animated: true, completion: nil) // Present alert controller
发布于 2019-06-07 09:08:55
下面是您想要实现的行为的示例代码。只需将您的警报控制器代码包含在didSelect中,您就可以开始工作了!
import UIKit
import PlaygroundSupport
class MyViewController : UITableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell()
}
cell!.textLabel?.text = "Hello World!"
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.textLabel?.text = "Hello Universe!"
}
}
https://stackoverflow.com/questions/56452201
复制相似问题