首页 > 解决方案 > 向下滚动时带有不需要的额外对象的 UITableViewCell

问题描述

我有一个视图控制器,在 viewdidload 方法中我调用一个函数来进行一些调用以在线检索数据。检索数据后,我将它们附加到数组中并重新加载表视图

起初,一切看起来都很棒,但是当我向下滚动时,我会看到您在下面看到的内容。

extension CastTableViewController : UITableViewDelegate, UITableViewDataSource {
    func conigure_cast_table () {
        castTable.translatesAutoresizingMaskIntoConstraints = false
        castTable.delegate = self
        castTable.dataSource = self
        
        castTable.register(ActorCell.self, forCellReuseIdentifier: ActorCell.cellid)
        view.addSubview(castTable)
        castTable.frame = view.bounds
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cast.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = castTable.dequeueReusableCell(withIdentifier: ActorCell.cellid, for: indexPath) as! ActorCell
        
        
        let name = cast[indexPath.row].name
        let character_name = cast[indexPath.row].character
        let pic = cast[indexPath.row].picture_path
        
        cell.configure(name: name, charName: character_name, pic_url: pic)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    
}

在此处输入图像描述

标签: iosswiftuitableviewuikit

解决方案


我通过使用 prepareforreuse 解决了这个问题

// in the custom cell class
    override func prepareForReuse() {
        super.prepareForReuse()
        
        for subview in stack.arrangedSubviews {
            stack.removeArrangedSubview(subview)
        }
        
        actorPic.image = nil
        realName.banner_title.text = nil
        realName.info.text = nil
        character.banner_title.text = nil
        character.info.text = nil
    }

推荐阅读