Search code examples
swiftuisegmentedcontrol

UISegmentedControl selectedIndex always showing 0


Just started learning iOS. I have created a UISegmentedControl programmatically and have initialized it with two items. I don't seem to understand why the selected index always shows 0.

Here is my code:

let items = ["Watchlist", "Favorites"]

var segmentedControl: UISegmentedControl {
        let sc = UISegmentedControl(items: items)
        sc.selectedSegmentIndex = 0
        sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
        return sc
    }    


// Action for segment change
@objc fileprivate func handleSegmentChange() {
        print(segmentedControl.selectedSegmentIndex)
    }


Solution

  • The segmented control is defined as a computed property which creates a new UISegmentedControl instance, with the selectedSegmentIndex value set to 0, every time it's accessed. Try using a property initialisation closure instead:

    let segmentedControl: UISegmentedControl = {
        let sc = UISegmentedControl(items: items)
        sc.selectedSegmentIndex = 0
        sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
        return sc
    }()