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.
Enter Swift as Language and choose Next. Go to the Storyboard and drag a Segmented Control to the top of the main view. Also drag a Label to the view and place it below the Segmented Control. Select the label and give it a text of First Segment selected.
Use yourSegmentname.selectedSegmentIndex = 1;
or whichever segment you want.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With