Monday, March 25, 2019

Highlight the selected cell in UICollectionView

This post is based on Xcode 9 and Swift 3. By default, when a user touches an item or a cell of a UICollectionView, some properties are updated and some events are triggered but there is no any UIs updated. It's the developer's job to update the UIs.

In the page below, there are a collection of themes displaying. When a user touches a theme, I want to show a green rectangle around it.


In the ViewController class, the UICollectionView.allowsMultipleSelection property should be set to false so that the user can select only one item/cell. When the user touches a cell, its isSelected property is set to true so the code to update the UIs for the cell should be done in the didSet block of the property as following:

class ThemeCollectionViewCell: UICollectionViewCell {
    ...
    
    @IBOutlet weak var rootStackView: UIStackView!
    
    override var isSelected:Bool {
        didSet {
            if isSelected {
                rootStackView.addBorders()
            } else {
                rootStackView.removeBorders()
            }
        }
    }
}
 

In case there is an item (cell) to be selected by default, the selectItem() method should be called in the ViewController.viewDidAppear() method to take effect then the isSelected property of the selected cell will be set to true.

Here is an example of how to add the borders to a stack view.

No comments:

Post a Comment