[ACCEPTED]-How can I set the default state of a UISegmentedControl?-interface-builder

Accepted answer
Score: 42

From code, you can do:

self.segmentedControl.selectedSegmentIndex = someDefaultIndex

Whether you should 7 set it in viewDidLoad: or not depends entirely on the 6 structure of your application. For example, if 5 your app is starting up and loading the 4 view for the first time and needs to set 3 the control to whatever value it had during 2 the previous run of the app, then it definitely 1 makes sense to do it there.

Score: 20

In Interface Builder when you select UISegmentedControl 5 object on your UI, then in attributes pane, in 4 segment control there's segment drop down 3 menu, select segment that you want selected 2 (0,1 and so on) and tick the 'selected' option 1 below it.

Score: 2

Select default value for your UISegmentedControl 1 via storyBoard

  1. Open ur storyboard and select the UISegmentedControl

enter image description here

  1. Select atributes inspector of your UISegmentedControl (in the right corner)

enter image description here

  1. Search the 'segment' atribute and open de dropdown.

enter image description here

  1. Select the item you want to be selected by default.

enter image description here

  1. Mark the selected checkbox to set selected by default.

enter image description here

Score: 0

If you don't use storyboards and want to 5 set a default index after some setup/networking 4 like me, this little snippet will select 3 something if the user hasn't. I placed this 2 in my subclass of UISegmentedControl, but you could place 1 this anywhere. (Swift 3)

Decl: var UISegmentedControlNoSegment: Int { get }
Desc: A segment index value indicating that there is no selected segment. See selectedSegmentIndex for further information.

Short version:

if selectedSegmentIndex == UISegmentedControlNoSegment {
    selectedSegmentIndex = initialIndex
}

Longer version

func reloadData() {
    guard let numberOfItems = dataSource?.numberOfItems() else {
        return
    }

    removeAllSegments()

    for index in 0...numberOfItems {
        insertSegment(with: $image, at: index, animated: false)
    }

    if selectedSegmentIndex == UISegmentedControlNoSegment {
        selectedSegmentIndex = initialIndex
    }
}
Score: 0

After clicking the Segmented Control go 4 to where you created the segments and choose 3 the one you want be default. Then below 2 that there will be a Box with "Selected" by 1 it. Select that and it will be default.

More Related questions