首页 > 解决方案 > func tableView 中的异步函数

问题描述

我在功能表视图中有一个异步功能。我想在我的单元格文本标签中使用函数的结果。但我不知道如何等到异步功能完成

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "groupDetail", for: indexPath)
    let group = trainingGroups[indexPath.row]
        cell.textLabel?.text = group.name
         self.getTrainerByID(trainerId: group.trainer_id_main, completion: { [self] (isRead, err,  trainer) in
            if isRead {
             cell.detailTextLabel?.text = trainer
                trainerMain = trainer!
             }else {
                 cell.detailTextLabel?.text = "Onbekend"
      cell.detailTextLabel?.text = group.trainer_id_main
      cell.layer.masksToBounds = true
      cell.layer.borderWidth = 0.25
      cell.layer.shadowOffset = CGSize(width: -1, height: 1)
      let borderColor: UIColor =  UIColor(red: 0, green: 45/255, blue: 114/255, alpha: 1)
      cell.layer.borderColor = borderColor.cgColor
      cell.accessoryType = .disclosureIndicator
      cell.tintColor = UIColor.white

      return cell

    }

 

如何让 te 单元的返回等到 getTrainerByID 完成?

Best regards,

Armand

标签: iosswiftuitableviewasynchronous

解决方案


您不太可能希望在该方法中进行任何异步调用。正如 Joakim 指出的那样,您应该尝试并做的是对您的初始数据发出后续请求,仅在完成后重新加载 tableView。例如:

private func requestData() {
   networkService.getTrainingGroups { [weak self] groups in 
      self?.networkService.getTrainers(for: groups) { trainers in
          self?.tableViewData = GroupAndTrainers(groups, trainers) 
          self?.tableView.reloadData()
      }
   } 
}

推荐阅读