UISegmentedControl deselect (make none of the segments selected)

為{幸葍}努か 提交于 2019-12-03 05:30:42

问题


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


回答1:


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.




回答2:


The right way to do this is:

[menu setSelectedSegmentIndex:UISegmentedControlNoSegment];



回答3:


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;



回答4:


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



回答5:


You can now do this in xcode 6 in the interface builder:

Deselect the 'Selected' option under segmented control behaviour in attributes inspector.




回答6:


swift 4

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



回答7:


The Swift solution: @IBOutlet weak var mySegmentedControl: UISegmentedControl! and mySegmentedControl.selectedSegmentIndex = -1.




回答8:


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 ;]



来源:https://stackoverflow.com/questions/2206066/uisegmentedcontrol-deselect-make-none-of-the-segments-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!