UISegmentedControl deselect (make none of the segments selected)
The right way to do this is:
[menu setSelectedSegmentIndex:UISegmentedControlNoSegment];
Edit:
Swift 5:
menu.selectedSegmentIndex = UISegmentedControl.noSegment
Setting the segmentedControl to .momentary = YES
changes the way the user can interact with the segmentedControl. If you want to have nothing selected initially when the page loads but have segmentedControl behave the same after a selection is made by the user then you will want something more like this:
Swift 4 solution:
@IBOutlet weak var segmentedControl: UISegmentedControl!
self.segmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment
Swift 5.1:
self.segmentedControl.selectedSegmentIndex = UISegmentedControl.noSegment
I guess you try to create a momentary selection in segmented control. In interface builder set the segmentedcontrol to momentary. Or in code you can do:
menu.momentary = YES;
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 ;]