Выберите элемент в collectionView, когда появится представление - PullRequest
0 голосов
/ 19 сентября 2018

Я пытаюсь выбрать свою первую ячейку в представлении коллекции, когда здесь появляется код для нее

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let indexPath = IndexPath(item: 0, section: 0)
        categoryCollectionView.selectItem(at: indexPath
            , animated: false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0))
        self.collectionView(categoryCollectionView, didSelectItemAt: indexPath)
    }

И у меня в классе collectionViewCell есть переопределение переменной isSelected для изменения текстаcolor

override var isSelected: Bool {
        didSet {
            if self.isSelected {
                self.categoryName.textColor = UIColor(red: 237/255, green: 28/255, blue: 36/255, alpha: 1.0)
            } else {
                self.categoryName.textColor = UIColor(red: 63/255, green: 62/255, blue: 62/255, alpha: 1.0)
            }
        }
    }

Но это не работает

Я решаю это, манипулируя свойством isSelected, и оно отлично работает

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.categoryCollectionView {
            if let cell = categoryCollectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionViewCell", for: indexPath) as? CategoryCollectionViewCell {
                cell.configureCell(text: categories[indexPath.row].name)
                if indexPath.row == 0 {
                    cell.isSelected = true
                }
                return cell
            }
        } 
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == self.categoryCollectionView {
            if indexPath != IndexPath(row: 0, section: 0) {
                collectionView.cellForItem(at: IndexPath(row: 0, section: 0))?.isSelected = false
            }
        }
    }

Ответы [ 2 ]

0 голосов
/ 20 сентября 2018

Вы можете попробовать, как показано ниже, и это будет работать для меня, если ячейка с индексом 0.

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = ScenarioCollectionView.dequeueReusableCell(withReuseIdentifier: "ReuseScenarioCollectionViewCell", for: indexPath as IndexPath) as! ScenarioCollectionViewCell

if (indexPath.row == 0){
    collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
    cell.layer.borderColor=UIColor.gray.cgColor        
}else{
    cell.layer.borderColor=UIColor.white.cgColor
}
    return cell
}

Я надеюсь, что это будет работать для вас.

0 голосов
/ 19 сентября 2018
            override func viewDidAppear(_ animated: Bool) {
              super.viewDidAppear(animated)

              let indexPathForFirstRow = IndexPath(row: 0, section: 0)

              categoryCollectionView.selectItem(at: indexPathForFirstRow, animated:false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0))

              self.collectionView(paymentHeaderCollectionView, didSelectItemAt: indexPathForFirstRow)     
    }

и внутри DidSelect, когда пользователь выбирает другую ячейку, вы можете отменить выбор ячейки, как эта

    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
    let firstCell = IndexPath(item: 0, section: 0)
    if indexPath != firstCell {
        collectionView.deselectItem(at: indexPath, animated: false)
       }
}

для части isSelect, которую вы можете попробовать.

override var selected: Bool {
    get {
        return super.selected
    }
    set {
        if newValue {
            super.selected = true
             //your Color
            println("selected")
        } else if newValue == false {
            super.selected = false
          //your Color
            println("deselected")
        }
    }
}

, хотя это можетпривести к проблемам, проще и лучше всего для этого, на мой взгляд, создать флаг isSelected внутри объектов, которые вы заполняете, проверять их и переключаться между ними внутри didSelect

...