如何在tableView单元格中实现收藏夹按钮



我需要实现一个保存按钮。当用户点击按钮时,它必须被填充,默认情况下它是未填充的。但当我运行我的应用程序时,tableView单元格中的一些按钮已经像一样被填充了

这是TableViewCell 的代码

var isFavorite: Bool = false
private let addToFavorites: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(systemName: "heart"), for: .normal)
button.tintColor = UIColor.white.withAlphaComponent(0.85)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
return button
}()
override func awakeFromNib() {
super.awakeFromNib()

setFavoriteButtonUI()
addToFavorites.addTarget(self, action: #selector(markFavorite), for: .touchUpInside)
}
@objc func markFavorite() {
setFavoriteButtonImage()
}
private func setFavoriteButtonImage() {
isFavorite = !isFavorite
let imgName = isFavorite ? "heart" : "heart.fill"
let favoriteButtonImage = UIImage(systemName: imgName)
self.addToFavorites.setImage(favoriteButtonImage, for: .normal)
}
private func setFavoriteButtonUI() {
addToFavorites.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(addToFavorites)

addToFavorites.topAnchor.constraint(equalTo: filmImgView.topAnchor, constant: 40).isActive = true
addToFavorites.trailingAnchor.constraint(equalTo: filmImgView.trailingAnchor, constant: -20).isActive = true
addToFavorites.heightAnchor.constraint(equalToConstant: 30).isActive = true
addToFavorites.widthAnchor.constraint(equalToConstant: 40).isActive = true
}

在cellForRowAt indexPath方法中,我添加了

tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.top)

这是iOS初学者的经典问题。

CCD_ 1具有重用对象池的机制。

当某个充满爱心的单元格从屏幕上滑出时,该单元格将进入重用对象池。

新单元格出现在屏幕上,可能是创建的,也可能是从重用对象池中提取的。


简单的解决方案是Mark & Config

为了维护单元格范围外的单元格状态数据,我们通常在控制器上有状态数据源。

@objc func markFavorite()更改状态数据源,然后table重新加载数据。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell中配置细胞心脏状态。


控制器:

var selected = [Int]()

func select(index idx: Int){
selected.append(idx)
table.reloadData()
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
// ...
cell.proxy = self
cell.config(willShow: selected.contains(indexPath.row), idx: indexPath.row)
}

Cell:

var proxy: XXXProxy? // learn sth proxy yourself
var idx: Int?
func config(willShow toShow: Bool, idx index: Int){
idx = index
btn.isHidden = !toShow
}
// add the rest logic yourself

最新更新