在 tabbar1 中更新数组后(自动)在 Tableview(tabbar2) 上重新加载数据(无需更改标签栏)

(Automatic) reloadData on Tableview(tabbar2) once Array is updated in tabbar1 (without needing to change tabbars)

tabbar1 - 我正在使用核心蓝牙连接到一些外围设备。连接后,我更新一个数组。

 func populateFoundBTArray(peripheral: CBPeripheral, service:CBService) {
     discoveredBTDevices.append(BTPeripheral.init(
                               id: discoveredBTDevices.count, 
                               name: peripheral.name!, 
                               uuid: peripheral.identifier, 
                               desc: service.uuid.description
                               connected: peripheral.state == .connected ? true : false ))
    }

在 TabBar2 中 - 我有一些原型(自定义)单元格通过静态单元格和动态单元格的组合通过 XIB 文件连接(类似于此解决方案 - )

在 TabBar2 中 - 我有 tableView.reloadData() 调用,这很棒,每当我切换到此 tabbar2 时,表格视图都会更新。 (但我必须亲自前往 tabbar1 --> tabbar2 才能触发此更新)

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    tableView.reloadData()
  }

我的目标是希望能够在数组 discoveredBTDevices 更新时重新加载表视图。

我试过了

let pop = tabbar2()
pop.tableView.reloadData() // also tried reloadSections(1 but didn't work

以及我在 SO 上找到的更多答案,但其中 none 有效。 (我没有尝试任何 segues / 通知,因为目前我只是将 discoveredBTDevices 作为全局变量来简化我的初始测试)

我正在 post 就我如何解决我的这个问题给出自己的答案。这不是一个完整的解决方案,而是一种解决方法,但我相信它是 suitable.

从最初的 post 开始,目标是在数组 discoveredBTDevices 更新后让 tableviewcell 刷新。回顾一下,目前 table 只会在用户切换到 tabbar1 然后返回到 tabbar2 时刷新(由于 reloadData()viewDidAppear 中调用)

UITableview 上搜索并阅读了 40 多个 SO 页面但没有找到答案后,我决定利用 UIButton 进行手动 table 重新加载。

  // https://whosebug.com/a/53032365/14414215
  //
  // https://whosebug.com/a/44735567/14414215
  //
  override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if section == deviceSection { // this is my paired device section of the static table
      let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 30.0))
      
      let sectionHeader = UILabel(frame: CGRect(x: 8, y: 0, width: 200, height: 30.0))
      sectionHeader.text = "PAIRED BLUETOOTH DEVICES"
      sectionHeader.font = UIFont.systemFont(ofSize: 12)
      sectionHeader.textColor = UIColor.systemGray
      
      let reloadButton = UIButton(frame: CGRect(x: tableView.frame.width-150, y: 0, width: 150, height: 30.0))
      reloadButton.setTitle("Reload", for: .normal)
      reloadButton.addTarget(self, action: #selector(ReloadButtonTapped), for: .touchUpInside)
      reloadButton.semanticContentAttribute = UIApplication.shared
          .userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft

      headerView.addSubview(reloadButton)
      headerView.addSubview(sectionHeader)
      return headerView
    }
    return super.tableView(tableView, viewForHeaderInSection: section)
  }


  @objc func ReloadButtonTapped(_ sender : Any) {
    tableView.reloadData()
  }

我已经链接了 2 个显示实现的 SO 页面并将其稍微合并,因为使用 viewForHeaderInSection 将删除使用 Apple 原生 header 的所有样式,因此添加了 sectionHeader