我正在尝试仅更新costumViewCell中的一个对象,
我已经尝试过collectionView.reloadItems(at: [IndexPath])
,但是此方法更新了我的整个单元格,从而产生了非常抖动的动画。
这是我的collectionView单元的示例代码,
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
var myButtonTitle: String? {
didSet{
if let title = myButtonTitle {
self.buttonA.setTitle(title, for: .normal)
}
}
}
var buttonActionCallBack: (()->()?)
override func awakeFromNib() {
super.awakeFromNib()
self.animation()
buttonA.addTarget(self, action: #selector(buttonACallBack), for: .touchUpInside)
}
@objc fileprivate func buttonACallBack() {
self.buttonActionCallBack?()
}
fileprivate func animation() {
UIView.animate(withDuration: 1.0) {
self.buttonA.transform = CGAffineTransform(translationX: 20, y: 20)
self.buttonB.transform = CGAffineTransform(translationX: 20, y: 20)
}
}
}
这是我的DataSource方法。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
let item = mainList[indexPath.row]
collectionView.reloadItems(at: <#T##[IndexPath]#>)
cell.buttonActionCallBack = {
() in
//Do Stuff and Update Just ButtonA Title
}
return cell
}
欢呼。
答案 0 :(得分:0)
抖动动画的发生是因为在collectionView.reloadItems(at: [IndexPath])
内写了这行cellForItemAt
,这确实是错误的方法,因为多次调用cellForItemAt
会导致无限循环重新加载IndexPath
' s。取而代之的是,您仅重新加载发生操作时所需的那一部分。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
let item = mainList[indexPath.row]
//collectionView.reloadItems(at: <#T##[IndexPath]#>) #removed
cell.buttonActionCallBack = {
() in
//Do Stuff and Update Just ButtonA Title
collectionView.reloadItems(at: [indexPath]) //Update after the change occurs to see the new UI updates
}
return cell
}