[英]How to set selected segment index in UISegmentedControl?
I'm trying to avoid an app crash here... I have a button that will remove a segment from a UISegmentedControl.我正在尝试避免应用程序崩溃...我有一个按钮可以从 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.但是,当按下另一个按钮执行检索 selectedSegmentIndex 的操作时,应用程序会崩溃。
In short: Is there any way to force the selection of a segment in a UISegmentedControl?简而言之:有没有办法强制在 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.编辑似乎 UISegmentedControl 在没有选择任何段时返回 -1 的 selectedSegmentIndex ......让我们看看我可以从这里做些什么。
Use yourSegmentname.selectedSegmentIndex = 1;
使用yourSegmentname.selectedSegmentIndex = 1;
or whichever segment you want.或您想要的任何片段。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.