Кнопка Set в collectionViewCell нажата и наоборот - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть collectionView и ячейка с моими категориями. here they are

Мне нужно установить Pressed и unpressed. два гос. Моя клетка состоит из ярлыка. Без кнопок. вот мой код Я думаю, что это очень легко сделать.

class CategoryCollectionViewCell: UICollectionViewCell, NibLoadable {

enum state {
case pressed
case unpressed
}

@IBOutlet weak var label: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    Decorator.decorate(self)
    addTargets()
}

func setText(text: String) {
    label.text = text
}

func setFont(font: UIFont) {
    label.font = font
}

func setFontColor(color: UIColor) {
    label.textColor = color
}

func setColor(backgroundColor: UIColor, borderColor: CGColor, borderWidth: CGFloat) {
    self.backgroundColor = backgroundColor
    self.layer.borderColor = borderColor
    self.layer.borderWidth = borderWidth
}

private func addTargets() {
    let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
    self.addGestureRecognizer(tap)
}

@objc func tapped() {

}

}

Как вы можете видеть, я сделал функцию для изменения цвета в ячейке.

вот мои методы в V C

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return categories.count
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let category = categories[indexPath.item]

    if category.id == "userId" {

      let cell = collectionView.dequeueReusableCell(withReuseIdentifier:CategoryCollectionViewCell.name, for: indexPath) as! CategoryCollectionViewCell
        cell.label.text = category.name
        return cell
    } else if category.id == "UniqueID" {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCollectionViewCell.name, for: indexPath) as! CategoryCollectionViewCell
        let tap = UITapGestureRecognizer(target: self, action: #selector(addNewCategory))
        cell.label.isUserInteractionEnabled = true
        cell.label.text = "+ add"
        cell.label.addGestureRecognizer(tap)
        cell.setColor(backgroundColor: .white, borderColor: monPurple.cgColor, borderWidth: 1.0)
        cell.setFontColor(color: .purple)
        return cell
    }
    return UICollectionViewCell.init()
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets (top: 10, left: 16, bottom: 10, right: 16)
}

есть мысли мои друзья?

1 Ответ

0 голосов
/ 21 февраля 2020

Прежде всего, почему вы используете жест касания, когда вы можете использовать делегат представления коллекции для этого метода делегата didSelectItem.

Я предполагаю, что вы этого не знаете, поэтому я прилагаю пример для этого

func collectionView(UICollectionView, didSelectItemAt: IndexPath)

здесь, в этой функции, вы можете получить касание самой collectionviewcell.

Теперь к вашей проблеме вам необходимо поддерживать класс модели, который поможет вам сохраниться. ваши данные.

Пример -

struct CategoryModel {

    var categoryName : String
    var isCategorySelected : Bool //or you can use your enum here
}

в вашем v c инициализировать этот массив моделей, предполагая, что

var dataModels : [CategoryModel] // you fill it

теперь в вашем cellforItemAt

управлять выбранным и невыбранным состоянием вашей ячейки

например

if dataModels[indexPath.item].isCategorySelected == true {
    //manage selected cell state
}else  {
    //manage unselected cell state

}


func collectionView(UICollectionView, didSelectItemAt: IndexPath) {

    dataModels[indexPath.item].isCategorySelected = !dataModels[indexPath.item].isCategorySelected //change your model data here according to the tap
    // now reload your cell here for that specific indexpath

}
...