首页 > 解决方案 > 在 Swift 中加载其他元素之后,在 TableViewCell 中异步加载一个元素

问题描述

我想加载一个包含同步和异步(远程)数据的表格视图。同步数据立即加载。异步数据准备好后如何加载?我在 cellforRow 或 view 中放了一些东西会出现吗?

现在我在表格视图单元格中设置标签值,但数据没有更新

这是我的 cellforRow 代码:

internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        let row = indexPath.row
        cell.textLabel?.text = Places[row].name
                Utilities.shared.getWeather(query: Places[row].name as NSString) { (response1) in
                    print(response1)
                   DispatchQueue.main.async  {
                    cell.detailTextLabel?.text = response1
                    }          
        }

        return cell
    }

标签: iosswiftuitableviewasynchronous

解决方案


当前行为在每次滚动时加载数据,在最坏的情况下,在同一时刻多次加载相同的数据,因此您需要通过将该逻辑放入模型中以获取所需内容并使用它更新它的内容来保留它一次,然后重新加载表/indexPath 一个例子描述这里


推荐阅读