代码之家  ›  专栏  ›  技术社区  ›  Egor Kolyshkin

集合视图单元格中的网络任务

  •  0
  • Egor Kolyshkin  · 技术社区  · 5 年前

    我有一个视图控制器,里面有表视图。在它的演示者中,我为要表示的单元格加载项目数组。然后在 cellForRowAtIndexPath: 在视图控制器中,我得到:

    override func viewDidLoad() {
        super.viewDidLoad()
        setUp()
        presenter.loadAllDocuments()
    }
    

        func loadAllDocuments() {
        documentService.loadAllDocuments { [weak self] documents in
            self?.documents = documents
            self?.cellPresenters = documents.compactMap { MaterialCellPresenter(with: $0) }
            DispatchQueue.main.sync {
                self?.view.reloadData()
            }
        }
    }
    

    在CellForRowaTindexPath中:

    if var cellPresenter = presenter.cellPresenters[indexPath.row] {
            cellPresenter.view = cell
            cell.presenter = cellPresenter
        }
    
        return cell
    

    var presenter: MaterialCellPresenterProtocol! {
        didSet {
            setUp()
        }
    }
    
    private func setUp() {
        documentIcon.image = presenter.documentIcon
        documentTitle.text = presenter.displayName
        presenter.getDocumentInfo()
    }
    

    func getDocumentInfo() {
        if let id = document.questionID {
            documentService.question(with: id) { [weak self] question in
                self?.documentQuestion = question
                DispatchQueue.main.async {
                    self?.view.updateDocumentInfo()
                }
    
            }
        }
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   vadian    5 年前

    • 将网络请求代码移到模型类或结构中。
    • cellForRow 将当前模型项的闭包指定给单元中的可选属性。
    • 您甚至可以在中取消网络请求 tableView(_:didEndDisplaying:forRowAt:)