UITableViewCell 上显示视频封面 - 优化性能和复用性
要在 UITableViewCell 上生成视频封面并确保不影响复用和退出当前页面,可以遵循以下步骤:
- 在 UITableViewCell 的子类中添加一个 UIImageView 属性,用于显示视频封面。
- 在 UITableViewCell 的子类中添加一个方法,用于设置视频封面。
- 在 UITableViewCell 的子类中添加一个方法,用于清除视频封面。
- 在 UITableViewController 中的 cellForRowAt 方法中,为每个 UITableViewCell 设置视频封面。
- 在 UITableViewController 中的 didEndDisplaying 方法中,清除不可见 UITableViewCell 上的视频封面。
下面是示例代码:
class CustomTableViewCell: UITableViewCell {
var thumbnailImageView: UIImageView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
thumbnailImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.contentView.frame.width, height: self.contentView.frame.height))
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.clipsToBounds = true
self.contentView.addSubview(thumbnailImageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setVideoThumbnail(image: UIImage) {
thumbnailImageView.image = image
}
func clearVideoThumbnail() {
thumbnailImageView.image = nil
}
}
class CustomTableViewController: UITableViewController {
var videoURLs: [URL] = []
var videoThumbnails: [Int: UIImage] = [:]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoURLs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
if let thumbnail = videoThumbnails[indexPath.row] {
cell.setVideoThumbnail(image: thumbnail)
} else {
DispatchQueue.global().async {
let thumbnail = self.generateThumbnail(url: self.videoURLs[indexPath.row])
self.videoThumbnails[indexPath.row] = thumbnail
DispatchQueue.main.async {
if let currentIndexPath = tableView.indexPath(for: cell), currentIndexPath == indexPath {
cell.setVideoThumbnail(image: thumbnail)
}
}
}
}
return cell
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let customCell = cell as? CustomTableViewCell {
customCell.clearVideoThumbnail()
}
}
func generateThumbnail(url: URL) -> UIImage? {
// 从视频链接生成视频封面的逻辑
// ...
return nil
}
}
这样,当 UITableView 显示 UITableViewCell 时,将会根据视频链接异步生成视频封面并设置到对应的 UITableViewCell 上。当 UITableViewCell 不再可见时,视频封面将被清除,以确保不影响复用和退出当前页面。
原文地址: https://www.cveoy.top/t/topic/jwbp 著作权归作者所有。请勿转载和采集!