41

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
esqew
  • 42,425
  • 27
  • 92
  • 132

2 Answers2

88

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

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31
neillo
  • 931
  • 8
  • 5
  • 3
    This would change UISegment selected index would to 1, but the segment would not marked selected. place share , in case you have the solution for the same. – Nijar Mar 18 '19 at 12:11
4

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
            }
        }
Kishore Kumar
  • 4,265
  • 3
  • 26
  • 47