0

I'm new to swift and I'm trying to make a particular subview which is a collectionViewcell selected through calling a function inside the parent collectioncell.

I am calling setChosenToBeTrue() which sets the isChosen variable to be true in the subview, but for some weird reason the variable's value doesn't really get set? What can be the issue? Thanks! I looked at some resources that passes data through story board or there are some old ones that are not in swift and I'm still confused.

Here's my code

In the parent collectioncell,

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

        let rightCell = collectionView.dequeueReusableCell(withReuseIdentifier: rightCell, for: indexPath) as! RightCell                       
        rightCell.setChosenToBeTrue()
        return rightCell
    }

In the subview

var isChosen: Bool = false
override init(frame: CGRect) {
      super.init(frame: frame)
      setupViews()
 }

func setChosenToBeTrue() {
    self.isChosen = true //function is called but setting it here,  
     //when it reaches setUpViews(), this boolean is still false
}

func setupViews(){
        self.isChosen = true // setting it here works (obviously)
        print(isChosen)
        backgroundColor = UIColor.gray
}
Jaydeep Vyas
  • 4,411
  • 1
  • 18
  • 44
xcalysta
  • 59
  • 3
  • 10
  • Possible duplicate of [Passing Data between View Controllers](https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – Nicolas Miari Aug 03 '17 at 04:51
  • you are calling setChosenToBeTrue in CellforRowAt true Did you checked using breakpoints that after the execution. of setChosenToBeTrue() do your setUpViews() is getting called ? If no just call your setUpViews() at end of your setChosenToBeTrue() – iOS Geek Aug 03 '17 at 04:54
  • Using breakpoints the setChosenToBeTrue is called first and then the setupViews. I don't want to hack my solution by calling setupViews after setChosenToBeTrue() because i don't always set the cell to be true, only selected ones – xcalysta Aug 03 '17 at 04:57
  • @xcalysta Since you are reusing your cell instances, make sure to override `prepareForReuse()` in your `UICollectionViewCell` subclass, so you can do the cleanup first and prepare it to be configured again properly. – choofie Aug 03 '17 at 06:17

1 Answers1

0

It's simple. init() and setupViews() methods are called before the setChosenToBeTrue() is called. So, you update this variable after setting up views.

Try this, for example:

var isChosen: Bool = false {
        didSet {
            setupViews()
        }
    }
Aleksandr Honcharov
  • 2,343
  • 17
  • 30