我有一个自定义集合视图,顶部有一个标记收藏夹按钮,按下时应该在中心显示一个像心脏动画一样的Instagram。到目前为止我所做的事情导致心脏动画出现在其他一些随机单元中,当然是由于这个重用标识符的代码。
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shopCell", for: indexPath) as! ShopCell
但是我应该如何解决这个问题呢?我已阅读多篇关于它的帖子并实施了解决方案,但它们都没有为我工作。例如,设置指向单元格的索引路径,然后使用按钮上的委派单击
cell.indexPath = indexPath
在我的商店单元格中我有
@IBAction func favHeartBtn(_ sender: Any) {
delegate.favoriteButton(sender: self)
}
在我的shopView中我有这个
func favoriteButton(sender: ShopCollectionViewCell) {
sender.centerHeart.isHidden = false
sender.centerHeart.zoomIn()
}
静态动画在其他单元格中开始。即使我检查了indexPath
答案 0 :(得分:1)
您需要在自定义UICollectionViewCell
中处理中心的显示/隐藏,即
class CustomCollectionCell : UICollectionViewCell
{
@IBOutlet weak var centerHeart: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
self.centerHeart.alpha = 0.0
}
@IBAction func onTapHeartButton(_ sender: UIButton)
{
UIView.animate(withDuration: 0.5, animations: {
self.centerHeart.alpha = 1.0
}) { (completed) in
if completed
{
UIView.animate(withDuration: 0.5, animations: {
self.centerHeart.alpha = 0.0
})
}
}
}
}
您可以根据需要添加所需的任何动画。
答案 1 :(得分:0)
在您的类中创建带索引的数组:
var favoriteList = [Int]()
在单元格设置代码中,将按钮的标记设置为indexPath.row
[skip cell setup code]
cell.centerHeart.tag = indexPath.row
你最喜欢的按钮看起来像:
func favoriteButton(sender: ShopCollectionViewCell) {
///update model
favoriteList.append(sender.tag)
///refresh UI
self.tableView.reloadData()
}
在此委托中,您检查IndexPath。如果您在列表中找到此indexPath,则显示按钮。
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if self.shouldAnimateCell(indexPath) {
cell.showHearthAnimation(indexPath)
} else {
cell.hideHearthAnimation()
}
}
func showHearthAnimation(indexPath: IndexPath) {
let cell = self.tableView.cellForRow(indexPath)
cell.displayCenterHearth()
}
func hideHearthAnimation(indexPath: IndexPath) {
let cell = self.tableView.cellForRow(indexPath)
cell.hideCenterHearth()
}
func shouldAnimateCell(indexPath: IndexPath) {
return self.favoriteList.contains(indexPath.row)
}
对于您实施的单元格:
func displayCenterHearth() {
self.centerHeart.isHidden = false
self.centerHeart.zoomIn()
}
func hideCenterHearth() {
self.centerHeart.isHidden = true
}
此解决方案应该适合您。很抱歉可能出现错误,我使用TextEditor编写此代码。
原始解决方案的主要问题是什么?我们正在使用MVC。这意味着我们有模型和视图。当您按下按钮时,您将更新UI(视图),但您不会对数据模型执行任何操作。正确的方案是:更新模型并重新加载或刷新视图。
我相信你已经有了数据模型,它看起来像:
var model: [Record]
struct Record {
var title: String
var description: String
var isFavorite: Bool
}
要使其适用于您的数据模型,请在委托方法中将isFavorite属性设置为true并重写shouldAnimateCell。
func favoriteButton(sender: ShopCollectionViewCell) {
///update model
let indexPath = self.tableView.indexPath(for: sender)
self.model[indexPath.row].isFavorite = true
///refresh UI
self.tableView.reloadData()
}
func shouldAnimateCell(indexPath: IndexPath) {
return self.model[indexPath.row].isFavorite
}
答案 2 :(得分:0)
虽然PGDev的答案很完美,但我接受了它是正确的答案。导致PGDev代码无法在我的自定义类中工作的问题是我使用委托代理按钮。
cell.delegate = self
我删除了这一行,并添加了PGDev在按钮的单元格IBOutlet中提供的动画代码,这样做了。