UISegmentedControl deselect (make none of the segments selected)

Viewed 31789

in fact the title contains my question. I have a UISegmentedControl, and need to deselect currently selected tab. I tried:

[menu setSelectedSegmentIndex:-1];

menu being the UBOutlet for uisegmentedcontrol but this gives me exception. anyone have some idea? thanks peter

8 Answers

swift 4

@IBOutlet weak var segmentControl: UISegmentedControl! {
    didSet {
        segmentControl.selectedSegmentIndex = UISegmentedControl.noSegment
    }
}

I did class which supports this kind of interaction:

class UIDeselectableSegmentedControl: UISegmentedControl {

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let previousSelectedSegmentIndex = self.selectedSegmentIndex

        super.touchesEnded(touches, with: event)

        if previousSelectedSegmentIndex == self.selectedSegmentIndex {

            self.selectedSegmentIndex = UISegmentedControl.noSegment
            let touch = touches.first!
            let touchLocation = touch.location(in: self)
            if bounds.contains(touchLocation) {
                self.sendActions(for: .valueChanged)
            }
        }
    }
}

The main advantage of that is that you just need to modify which class the Storyboard/Xib/ViewCode is using and this will work like a charm ;]

I would assume that you've called [myArray length] instead of the proper [myArray count] somewhere in your code. NSArray uses the count method, not length for the number of items it contains.

Related