首页 > 解决方案 > 如何在调用 cellforRowAt 之前清除表格视图单元格?

问题描述

我有以下代码

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        //creating a cell using the custom class
        if (indexPath.row == 0 && indexPath.section == 0) {


            var cell:UITableViewCell;
            cell = tableView.dequeueReusableCell(withIdentifier: "book", for: indexPath)
            cell.selectionStyle = UITableViewCell.SelectionStyle.none;


            self.ref.observe(DataEventType.value, with: { (snapshot) in
                self.ref.child("featured").observeSingleEvent(of: .value, with: { (snapshot) in
                    // Get user value
                    let value = snapshot.value as? NSDictionary
                    let title = value?["title"] as? String ?? ""
                    self.featured = value?["url"] as? String ?? ""

                    let label = UILabel(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: 24))
                    label.numberOfLines = 0
                    label.font = UIFont(name: "CeraPro-Medium", size: 20);
                    label.textColor = UIColor.black
                    label.text = NSLocalizedString("   Free Daily Pick", comment: "featured")
                    label.adjustsFontForContentSizeCategory = true
                    cell.addSubview(label)

                    if let image = value?["image"] as? String, image.isEmpty {
                        print("String is nil or empty.")
                    } else {
                        if let image = value?["image"]  {

                            let imageView = UIImageView();
                            imageView.frame = CGRect(x: 0,
                                                     y: 75,
                                                     width: cell.frame.size.width,
                                                     height: 150)
                            imageView.contentMode = .scaleAspectFill
                            imageView.isUserInteractionEnabled = false

                            imageView.sd_setImage(with: URL(string: image as! String), placeholderImage: nil)
                            cell.addSubview(imageView)

                            let label = UILabel(frame: CGRect(x: 10,
                                                              y: cell.frame.size.height-60,
                                                              width: cell.frame.size.width,
                                                              height: 50));
                            label.textColor = UIColor.black
                            label.backgroundColor = UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5)
                            label.font = UIFont(name: "CeraPro-Bold", size: 16)
                            label.text = "  \(title)"

                            let view = UIView()
                            view.frame = CGRect(x: 0, y: 0, width: cell.frame.size.width, height: 150);
                            view.tag = 123
                            view.addSubview(imageView)
                            view.addSubview(label)
                            cell.contentView.addSubview(view)
                        }
                    }
                    // ...
                }) { (error) in
                    print(error.localizedDescription)
                }

            })

            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "book", for: indexPath) as! BookTableViewCell

            cell.cellIndex = indexPath
            cell.dataSource = self
            cell.delegate = self
            cell.backgroundColor = UIColor.white
            var books = [Book]();

            let count = self.enterpriseBooks.count;
            if count > 0 && indexPath.section <= self.enterpriseBooks_2.count {
                books = self.enterpriseBooks_2[indexPath.section - 1]!;
            }

            if (indexPath.section == (count + 1)) {
                books = nytbooks;
            } else if (indexPath.section == (count + 2)) {
                books = trendingbooks;
            } else if (indexPath.section == (count + 3)) {
                books = newbooks
            }

            if (books.count > 0) {
                if (cell.collectionView === nil) {
                    cell.addCollectionView();
                    cell.collectionView.reloadData()
                }
            }
            return cell
        }
}

这里对于第 0 行第 0 行 - 我展示了一个特色图片 对于第 1、2、3 部分 - 我展示了书籍图像的水平集合视图。

发生的事情是通过使用 dequeue 函数来获取表格视图单元格,表格视图正在缓存一些相互重叠的表格视图单元格内容。有没有办法在调用 cellForRowAt 之前清除表格视图单元格?

标签: swifttableview

解决方案


以编程方式将子视图添加到单元格对我来说似乎是一个糟糕的主意。尽可能尝试使用自动布局和 xib 文件。

无论如何,理论上您可以从出列单元格中删除所有子视图,然后再次添加它们。

for view in cell.subviews {
    view.removeFromSuperview()
}

也就是说,有更好的方法可以在第一个位置使用特殊单元格,例如使用不同的单元格类型


推荐阅读