override selectedSegmentIndex

503 views Asked by At

I have a subclass of UISegmentedControl and want to catch a event of selecting segment.

I overrided selectedSegmentIndex and use didSet but it is not invoked and value is changed without calling didSet.

class SLSegmentControl: UISegmentedControl {
    override var selectedSegmentIndex: Int {
        didSet {
            print(selectedSegmentIndex)
        }
    }

If I set

isMomentary = true

the didSet is invoked with value -1 whichever segment selected.

Currently I'm using addTarget to catch this event. However this will be disabled once outside of this class adds Target to this class, so I want to avoid to use this.

addTarget(self, action: #selector(didSegmentSelect(sender:)), for: .valueChanged)

As long as I remember it worked in objective-c but not working in swift 3. Am I missing something?

I can track user interaction with adding observer to selectedSegmentIndex.

1

There are 1 answers

0
mfaani On

If I set

isMomentary = true

the didSet is invoked with value -1 whichever segment selected.

If you set isMomentary = true then your segmented control will act more like a horizontal stackview of buttons and upon any tapping it will trigger a valueChanged callback with the correct index, but then immediately set it to noSegment ie -1.

With isMomentary = true if you tap on a button, it gets highlighted then goes back to its normal state. It doesn't have a selected state. Normally it's not what you want. It's just a convenience to horizontal stackview of buttons. It's a bit counter intuitive I'd say.