首页 > 解决方案 > 离开并返回视图后 TableView 无法正常工作

问题描述

如果您离开他们的视图并回来,我对 tableView 的行为感到困惑。

我有一个带有一个 tableView 的屏幕,当我第一次进入视图时它可以工作。添加、删除和更新表格单元格有效。但是,当我按下一个按钮进入下一个视图并立即返回时,它tableView不再起作用。应该执行的代码(tableView.reload()以及所有相关的方法)按应有的方式运行。但是,即使在内部更新了数组,屏幕也不会更新,并且重新加载会运行并执行应该更新屏幕的代码(也就是说,tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell运行得很好)。

我错过了什么?如果我离开视图并返回到 ti,tableView 是否需要任何特殊处理?

谢谢。

编辑:

tableView 类的代码类似于:

class DebugViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var table: UITableView!
var array    = [M]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.searchbar.delegate = self
    self.table.delegate     = self
    self.table.dataSource   = self
    search_view = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Search_view") as? SomeViewController
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cellManage") as? TableCellManage else { return UITableViewCell() }

    let idx  = indexPath.row
    let value =  array[idx]

    cell.lbl_time.text             = value.month
    cell.lbl_background.text       = value.color

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 130
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.array.count
}

@IBAction func tapped_addsongs(_ sender: Any) {
    self.present( search_view, animated: true, completion: nil)
}

}

标签: iosswiftiphonexcode

解决方案


tableView.reload()部分在哪里?由于您尝试在后台线程中更新表,因此可能会生成此问题。所有 UI 更新必须在主线程中完成:

func someFunc() { 
...
  DispatchQueue.main.async {
   tableView.reload()
  }
...
}

推荐阅读