ios 如何在 UISegmentedControl 中设置选定的段索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2240862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:53:56  来源:igfitidea点击:

How to set selected segment index in UISegmentedControl?

iosiphone-sdk-3.0uisegmentedcontrol

提问by esqew

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.

我正在尝试避免应用程序崩溃...我有一个按钮可以从 UISegmentedControl 中删除一个段。如果按下该按钮并且用户选择了要删除的段,则该段将被删除并且不会突出显示任何选择。但是,当按下另一个按钮执行检索 selectedSegmentIndex 的操作时,应用程序会崩溃。

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

简而言之:有没有办法强制在 UISegmentedControl 中选择一个段?

editit 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.

编辑似乎 UISegmentedControl 在没有选择任何段时返回 -1 的 selectedSegmentIndex ......让我们看看我可以从这里做些什么。

回答by neillo

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

像这样使用.. yourSegmentname.selectedSegmentIndex = 1;// 或者你想要的任何段

回答by Kishore Kumar

This code is for swift 2.0

此代码适用于 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
            }
        }