【问题标题】:Why are the icons from my cell changing after scrolling? [duplicate]为什么滚动后我的单元格中的图标会发生变化? [复制]
【发布时间】:2020-06-17 10:27:26
【问题描述】:

我制作了一个列表,用户可以在其中查看事件开始暂停还是停止

刚刚创建的事件没有图标也没有状态,返回时带有创建的时间戳

我遇到的问题是,当滚动出视图时,没有图标的空白单元格将其图标更改为“停止”。

events.asObservable()
            .bind(to:tableView.rx.items) { (tableView, row, event) in
                let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell") as! EventCell
                cell.detailLabel.text = "created: \(self.dateFormat.string(from: event.created!)) Uhr"
                cell.titleLabel.text = event.name
                if let date = event.started {
                    cell.icon.image = UIImage(named: "start") 
                    var dateStr = "started: \(self.dateFormat.string(from: date))"

                    if let paused = self.isPaused(event: event) {
                        if paused {
                            dateStr = "\(dateStr), paused"
                            cell.icon.image = UIImage(named: "pause")
                        }
                    }

                    if let dateEnded = event.ended {
                        dateStr = "\(dateStr), ended: \(self.dateFormat.string(from: dateEnded))"
                        cell.icon.image = UIImage(named: "stop")
                    }
                }
                return cell

            }.disposed(by: disposeBag)

发生了什么?

【问题讨论】:

标签: swift


【解决方案1】:

这是由于单元重复使用造成的。您可能应该覆盖EventCell 中的prepareForReuse 方法,并将图像设置为初始图像或nil,然后再在下一个cellForRow(或UICollectionView 中的cellForItem)重用以解决此问题。

class EventCell: UITableViewCell { // (or UICollectionViewCell if issue is in UICollectionView)
    //...
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil // or a default placeholder image.
    }
}

替代方法:您还可以在 UITableView 中的 cellForRow(或 UICollectionView 中的 cellForItem)方法中解决此问题,方法是将 imageView.image 设置为 nil 或顶部的占位符图像并继续。

对于 UITableView:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
    cell.imageView.image = nil // or a default placeholder image.
    //...
    return cell
}

对于 UICollectionView:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
    cell.imageView.image = nil // or a default placeholder image.
    // ...
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多