Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 320
esqew Avatar asked Feb 10 '10 22:02

esqew


People also ask

How do you get the selected segment title in Swift?

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.


2 Answers

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

like image 89
neillo Avatar answered Sep 27 '22 21:09

neillo


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             }         } 
like image 28
Kishore Kumar Avatar answered Sep 27 '22 22:09

Kishore Kumar