以下是一个示例解决方案,展示了在表视图滚动后更改播放/暂停按钮图像的方法:
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var playPauseButton: UIButton!
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let data = [true, false, true, true, false] // 示例数据
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
let isPlaying = data[indexPath.row]
let buttonImage = isPlaying ? UIImage(named: "pause") : UIImage(named: "play")
cell.playPauseButton.setImage(buttonImage, for: .normal)
return cell
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
tableView.visibleCells.forEach { cell in
if let indexPath = tableView.indexPath(for: cell) {
let isPlaying = data[indexPath.row]
let buttonImage = isPlaying ? UIImage(named: "pause") : UIImage(named: "play")
(cell as? CustomTableViewCell)?.playPauseButton.setImage(buttonImage, for: .normal)
}
}
}
}
在上述示例中,数据源数组data
存储了每个单元格是否正在播放的信息。然后,根据该信息设置每个单元格的播放/暂停按钮图像。在scrollViewDidEndDecelerating
方法中,当表视图滚动停止后,对可见的单元格进行更新,以确保按钮图像正确更新。
上一篇:表视图高度不正确地进行动画
下一篇:表视图滚动之前不加载图像。