首页 > 解决方案 > 滚动时UITableView多节冲突

问题描述

有一个奇怪的问题UITableView。我有 3 个数据源,这意味着UITableView. 当我滚动时UITableView,按钮和图像发生冲突。按钮消失,图像变形。

这是我的cellForRowAt方法。

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "eventnetworkingcell", for: indexPath) as! EventNetworkCell

        var name: String = ""
        var job: String = ""
        var company: String = ""
        var img: Int?

        cell.userImageView.layer.cornerRadius = 45
        cell.userImageView.clipsToBounds = true

        if indexPath.section == 0 {

            name = self.matchmaking[indexPath.row].name
            job = self.matchmaking[indexPath.row].job
            company = self.matchmaking[indexPath.row].company
            img = self.matchmaking[indexPath.row].image


        }
        else if indexPath.section == 1 {

            name = self.networkInEvent[indexPath.row].name
            job = self.networkInEvent[indexPath.row].job
            company = self.networkInEvent[indexPath.row].company
            img = self.networkInEvent[indexPath.row].image

            cell.addButtonOutlet.alpha = 0
        }
        else {

            name = self.allAttendees[indexPath.row].name
            job = self.allAttendees[indexPath.row].job
            company = self.allAttendees[indexPath.row].company
            img = self.allAttendees[indexPath.row].image


        }

        cell.nameLabel.text = name
        cell.jobLabel.text = job
        cell.companyLabel.text = company

        if let imgid = img {
            let url = MTApi.url(for: imgid, size: .normal)
            cell.userImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: nil)
        }
}
        cell.addButtonOutlet.addTarget(self, action: 
  #selector(self.addNetwork(sender:)), for: .touchUpInside)

        return cell

    }

当我删除cell.addButtonOutlet.alpha = 0线时,按钮并没有消失。

还有一个视频显示了这个问题:

视频

标签: iosuitableviewswift4sdwebimage

解决方案


您遇到了细胞重复使用的问题。

基本上,正在发生的事情是,tableView 只创建了与屏幕上可见的单元格一样多的单元格,并且一旦单元格被滚动出视图,它就会被重用于数据源中的另一个项目。

按钮看似消失的原因是您之前已经删除了按钮,但是现在,在重用时没有告诉单元格再次显示按钮。

解决这个问题很容易,只需添加:

cell.addButtonOutlet.alpha = 0

到您的第 0 和第 2 部分(其他块)。

与图像相同,除非您告诉单元格在需要时删除图像,否则将保留前一个图像,因此只需添加以下内容:

if let imgid = img {
    let url = MTApi.url(for: imgid, size: .normal)
    cell.userImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: nil)
} else {
    cell.userImageView.image = nil
}

推荐阅读