How to set selected segment index in UISegmentedControl?

早过忘川 提交于 2019-11-27 02:03:01

问题


I'm trying to avoid an app crash here... I have a button that will remove a segment from a UISegmentedControl. If that button is pressed and the user has the segment to be removed selected, the segment will remove and no selection will be highlighted. However, when another button is pushed that does an action that retrieves the selectedSegmentIndex, the app crashes.

In short: Is there any way to force the selection of a segment in a UISegmentedControl?

edit it seems as though the UISegmentedControl is returning a selectedSegmentIndex of -1 when no segment is selected... let's see what I can do from here.


回答1:


Use like this.. yourSegmentname.selectedSegmentIndex = 1; // or whichever segment you want




回答2:


This code is for swift 2.0

@IBOutlet weak var segmentcontroll: UISegmentedControl!
    @IBAction func segmentneeded(sender: AnyObject)
        {

            if(segmentcontroll.selectedSegmentIndex==0)
            {
                self.view.backgroundColor=UIColor.purpleColor()
                segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
            }
            else if(segmentcontroll.selectedSegmentIndex==1)
            {
                    self.view.backgroundColor=UIColor.yellowColor()
                            segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
            }
            else
            {
                self.view.backgroundColor=UIColor.grayColor()
                            segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
            }
        }


来源:https://stackoverflow.com/questions/2240862/how-to-set-selected-segment-index-in-uisegmentedcontrol

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