Trying to override "selected" in UICollectionViewCell Swift for custom selection state

19,967

Solution 1

And for Swift 3.0:

override var isSelected: Bool {
    didSet {
        alpha = isSelected ? 0.5 : 1.0
    }
}

Solution 2

Figured it out by stepping into code. The problem was that the super.selected wasn't being modified. So I changed the code to this:

override var selected: Bool {
    get {
        return super.selected
    }
    set {
        if newValue {
            super.selected = true
            self.imageView.alpha = 0.5
            println("selected")
        } else if newValue == false {
            super.selected = false
            self.imageView.alpha = 1.0
            println("deselected")
        }
    }
}

Now it's working.

Solution 3

Try this one.

override var selected: Bool {
    didSet {
        self.alpha = self.selected ? 0.5 : 1.0
    }
}
Share:
19,967

Related videos on Youtube

Julius
Author by

Julius

Updated on June 22, 2022

Comments

  • Julius
    Julius about 2 years

    I am trying to implement a custom selection style for my cells in a UICollectionView. Even though it is easily possible to do this manually in the didSelect and didDeSelect methods I would like to achieve this by manipulating the "selected" variable in UICollectionViewCell.

    I have this code for it:

        override var selected: Bool {
        get {
            return super.selected
        }
        set {
            if newValue {
                self.imageView.alpha = 0.5
                println("selected")
            } else if newValue == false {
                self.imageView.alpha = 1.0
                println("deselected")
            }
        }
    }
    

    Now, when I select a cell, the cell gets highlighted but "selected" gets printed twice and the deselection does not work (even though both UICollectionView methods are implemented).

    How would I go about this? Thanks!

    • quantumpotato
      quantumpotato almost 9 years
      Have you tried putting a breakpoint and tracing when the first "selected" gets hit?
    • Julius
      Julius almost 9 years
      Thanks. Helped me solve the problem. super.selected was not being modified
  • quantumpotato
    quantumpotato almost 9 years
    Glad it's working! You should be able to mark your answer as correct soon
  • Pratik Jamariya
    Pratik Jamariya over 7 years
    great..!! helped that (Y) and thumbs up for answering own question
  • tomas789
    tomas789 over 7 years
    This one should be selected as an answer because it corresponds to newest version of iOS and uses only didSet.
  • JoakimE
    JoakimE about 7 years
    Maybe add an update to Swift 3. selected is no "isSelected"
  • Munib
    Munib almost 6 years
    Why is isSelected called when scrolling?