gpt4 book ai didi

Swift:为什么每次我向下和向上滚动时我的按钮都会重复?

转载 作者:行者123 更新时间:2023-11-30 10:41:49 26 4
gpt4 key购买 nike

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)

if checkIfOutOfRange.getElement(at: indexPath.row) != nil {
cellPlayerBtn[indexPath.row] = UIButton(type: .custom)
cellPlayerBtn[indexPath.row].translatesAutoresizingMaskIntoConstraints = false
cellPlayerBtn[indexPath.row].addTarget(self, action: #selector(hearVoice), for: .touchUpInside)
cellPlayerBtn[indexPath.row].setImage(UIImage(named: "play")?.withRenderingMode(.alwaysOriginal), for: .normal)
cellPlayerBtn[indexPath.row].contentHorizontalAlignment = .center
cellPlayerBtn[indexPath.row].layer.cornerRadius = 10
cellPlayerBtn[indexPath.row].layer.borderWidth = 2

if self.sortedUserVoice.count > 0 {
if self.sortedUserVoice[indexPath.row].userUid == self.finalUserUid {
cellPlayerBtn[indexPath.row].layer.borderColor = UIColor.blue.cgColor
cell.addSubview(cellPlayerBtn[indexPath.row])
cellPlayerBtn[indexPath.row].leftAnchor.constraint(equalTo: cell.leftAnchor, constant: 10).isActive = true
cellPlayerBtn[indexPath.row].centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
cellPlayerBtn[indexPath.row].heightAnchor.constraint(equalToConstant: 50).isActive = true
cellPlayerBtn[indexPath.row].widthAnchor.constraint(equalToConstant: 150).isActive = true
} else if self.sortedUserVoice[indexPath.row].userUid == self.userOppositeID {
cellPlayerBtn[indexPath.row].layer.borderColor = UIColor.green.cgColor
cell.addSubview(cellPlayerBtn[indexPath.row])
cellPlayerBtn[indexPath.row].rightAnchor.constraint(equalTo: cell.rightAnchor, constant: -10).isActive = true
cellPlayerBtn[indexPath.row].centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
cellPlayerBtn[indexPath.row].heightAnchor.constraint(equalToConstant: 50).isActive = true
cellPlayerBtn[indexPath.row].widthAnchor.constraint(equalToConstant: 150).isActive = true
}
}
}

return cell
}

最佳答案

我建议您从 cellForItemAt indexPath 中删除 addSubview 方法,并直接在 UICollectionViewCell 子类中实现它。现在,根据您的 FinalUserUid 或 userOppositeID,您可以隐藏或显示 UIButton。这样, Collection View 的单元格就可以得到重用,这是一种有效的方法。

关于Swift:为什么每次我向下和向上滚动时我的按钮都会重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com