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
}
答案 0 :(得分:0)
我建议您从cellForItemAt indexPath中删除addSubview方法,并直接在UICollectionViewCell子类中实现它。现在,根据您的finalUserUid或userOppositeID,您可以隐藏或显示UIButton。这样,收集视图的单元将被重用,这是一种有效的方式。