Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 848
Julius Avatar asked Jul 09 '15 23:07

Julius


4 Answers

And for Swift 3.0:

override var isSelected: Bool {
    didSet {
        alpha = isSelected ? 0.5 : 1.0
    }
}
like image 61
Morten Gustafsson Avatar answered Nov 20 '22 01:11

Morten Gustafsson


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.

like image 42
Julius Avatar answered Nov 19 '22 23:11

Julius


Try this one.

override var selected: Bool {
    didSet {
        self.alpha = self.selected ? 0.5 : 1.0
    }
}
like image 14
osrl Avatar answered Nov 19 '22 23:11

osrl


For Swift 5, put this code in the cell

override var isSelected: Bool {
    get {
        return super.isSelected
    }
    set {
        if newValue {
            super.isSelected = true
            self.lbl_Sub_Category.textColor = UIColor.white
            self.ly_Container.backgroundColor = UIColor.black
            print("selected")
        } else if newValue == false {
            super.isSelected = false
            self.lbl_Sub_Category.textColor = UIColor.black
            self.ly_Container.backgroundColor = UIColor.white
            print("deselected")
        }
    }
}

You can select the first item of the collection view using this code in the viewcontroller:

    grid_SubCategories.reloadData()
    
    let firstItem:IndexPath = IndexPath(row: 0, section: 0)
    grid_SubCategories.selectItem(at: firstItem, animated: false, scrollPosition: .left)
like image 1
Firas Shrourou Avatar answered Nov 20 '22 00:11

Firas Shrourou