从UIAlertAction处理程序更新UILabel在Swift 4中不起作用 [英] Updating UILabel from UIAlertAction handler not working in Swift 4

查看:202
本文介绍了从UIAlertAction处理程序更新UILabel在Swift 4中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iOS应用程序中有一个UITableView的子类(Swift 4,XCode 9).该表有一行,我希望它在单击时显示警报,从用户那里获取一些输入,然后在用户单击警报中的确定"时更新表中的标签(lblUserFromPrefs).目前,一切正常,除了标签未更新.这是我的UITableView子类中的相关代码:

I have a subclass of UITableView in my iOS app (Swift 4, XCode 9). This table has one row and I want it to display an alert when it's clicked, get some input from the user, and then update a label (lblUserFromPrefs) in the table when the user clicks "OK" in the alert. Currently everything works fine except the label doesn't get updated. Here is the relevant code from my UITableView subclass:

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)
    }
}

当我运行此命令时,会发生什么情况,即当警报关闭时,标签的文本不会改变,但是当再次单击表行时,标签的文本会立即改变.我不知道为什么要等到再次单击该行以更新文本.我期望的所有打印语句都会打印(包括在按下警报的确定"按钮时立即打印标签更新"),并且它们打印正确的内容.我知道,当您尝试从后台线程中的闭包更新UI时,必须使用DispatchQueue.main.async {},但是我不确定为什么即使使用主线程也无法更新UI.我尝试使用DispatchQueue.main.async(execute: {})并将self.lblUserFromPrefs.setNeedsDisplay()直接放在self.lblUserFromPrefs.text = "text"之后.有什么想法我做错了吗?谢谢!

What happens when I run this is the label's text doesn't change when the alert closes but does change immediately when the table row is clicked again. I don't know why it waits until the row is clicked again to update the text. All the print statements print when I expect (including printing "label updated" immediately when the alert's OK button is pressed) and they print the right things. I know that when you're trying to update the UI from a closure in a background thread you have to use DispatchQueue.main.async {} but I'm not sure why it's not updating even though I am using the main thread. I have tried using DispatchQueue.main.async(execute: {}) and putting self.lblUserFromPrefs.setNeedsDisplay() directly after self.lblUserFromPrefs.text = "text". Any ideas what I'm doing wrong? Thanks!!

推荐答案

以下是您要实现的行为的示例代码.只需将警报控制器代码包含在didSelect中,您就可以开始使用了!

Here is the sample code for the behavior you want to achieve. Just include your alert controller code in didSelect and you should be good to go!

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!"
  }
}

这篇关于从UIAlertAction处理程序更新UILabel在Swift 4中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆