Swift: Почему мои кнопки будут дублироваться каждый раз, когда я прокручиваю вверх и вниз? - PullRequest
0 голосов
/ 16 июня 2019
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
}

1 Ответ

0 голосов
/ 16 июня 2019

Я предлагаю вам удалить метод addSubview из cellForItemAt indexPath и реализовать его непосредственно в подклассе UICollectionViewCell.Теперь, в зависимости от вашего finalUserUid или userOpposingID, вы можете скрыть или показать UIButton.Таким образом, ячейка представления коллекции повторно используется, и это эффективный способ сделать это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...