我在我的应用程序中使用了 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()
中设置单元格的缩略图和标题 socket 。我了解单元格是如何从场景中滚动出来然后重新使用的,所以我使用 prepareForReuse
来清理单元格。
For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view's delegate in tableView(_:cellForRowAt:) should always reset all content when reusing a cell.
当需要清理 prepareForReuse
中的单元格时,我通过反复试验发现清理标签文本的最佳方法是使用 label.text = ""
而不是 label.text = nil
显然,从上面的内容来看,Apple 不希望 prepareToReuse
用于光清理以外的用途。但是,我已经阅读了关于 SO 的其他帖子,最好通过将 AVPlayerLayer 设置为 nil
并将其从 prepareForReuse
的 super 层中删除来清理和删除它。
我有两个问题
- 如果不在
prepareForReuse
中,那么我在哪里将currentTime
和data
属性重置为nil
和imageView 的图像
到nil
?这是假设应用程序已发送到后台并且currentTime
属性设置为某个值。 - 如果我不能在
prepareForReuse
中将标签的文本设置为 nil 那么为什么最好在prepareForReuse
中将 AVPlayerLayer 设置为 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
}
最佳答案
我在这里找到了答案:prepareForReuse clean up
似乎清理单元格的最佳方法是在设置内容之前在 cellForRowAtIndexPath 中执行此操作。
关于ios - Swift iOS - 如何清理单元格的类属性和 ImageView 的图像(也在单元格内)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605963/