Swift iOS - 如何清理单元格的类属性和 ImageView 的图像(也在单元格内)?



我在我的应用程序内使用CollectionViewCells和tableViewCells,但是在此示例中,我将列出tableViewCell信息,因为它们都使用prepareForReuse

我有:

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var backgroundViewForPlayerLayer: UIView!
var data: MyData?
var currentTime: CMTime? // used to keep track of the current play time when the app is sent to the background
var playerItem: AVPlayerItem?
var player: AVPlayer?
var playerLayer: AVPlayerLayer?

当我获取电池的表数据时,我将数据馈送到cellForRowAtIndexPath中的单元格。我将其传递给单元内的data属性,然后在awakeFromNib()中设置了单元格的缩略图和标题插座。我了解如何从现场滚出单元格,然后再重复使用,因此我使用prepareForReuse清洁单元格。

在这里苹果说:

出于绩效原因,您应仅重置单元格的属性 与内容无关,例如alpha,编辑和 选择状态。表查看的代表 tableview(_:cellforrowat :)时应始终重置所有内容 重用单元格。

是时候清理prepareForReuse中的单元格时,我通过反复试验发现清理标签文本的最佳方法是使用label.text = ""而不是label.text = nil,显然是从上面的Apple中使用prepareToReuse用于清洁不仅仅是轻度清洁。但是,我已经阅读了其他文章,以便最好通过将其设置为nil并将其从prepareForReuse中的超级层中删除来清理和删除Avplayerlayer。

我有2个问题

  1. 如果不在prepareForReuse内部,则在哪里将currentTimedata属性重置为nil,将imageView's image重置为nil?这是假设该应用程序已发送到背景,并且currentTime属性设置为某个值。
  2. 如果我不能将标签的文本设置为 prepareForReuse中的零,那么为什么最好将Avplayerlayer设置为 prepareForReuse中的nil?

tableviewcell:

class MyCell: UITableViewCell{
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var thumbnailImageView: UIImageView!
var data: MyData?
var currentTime: CMTime?
var playerItem: AVPlayerItem?
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(self, selector: #selector(appHasEnteredBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)
        titleLabel.text = data.title!
        thumbnailImageView.image = data.convertedUrlToImage() // url was converted to an image
        configureAVPlayer() //AVPlayer is configured
}

override func prepareForReuse() {
        super.prepareForReuse()
        titleLabel.text = ""
        player?.pause()
        playerLayer?.player = nil
        playerLayer?.removeFromSuperlayer()
        // should I reset these 3 here or somewhere else?
        data = nil
        currentTime = nil
        thumbnailImageView.image = nil
}
@objc func appHasEnteredBackground() {
        currentTime = player.currentTime()
        // pause the player...
}
}

CellForrowatIndExpath:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        let data = tableData[indexPath.row]
        cell.data = data
        return cell
}

我在这里找到答案:Preparforreuse清理

似乎最好的方法是在设置内容之前在CellForrowatIndExpath中进行操作。

最新更新