[ACCEPTED]-How can I set the default state of a UISegmentedControl?-interface-builder
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.
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.
Select default value for your UISegmentedControl 1 via storyBoard
- Open ur storyboard and select the UISegmentedControl
- Select atributes inspector of your UISegmentedControl (in the right corner)
- Search the 'segment' atribute and open de dropdown.
- Select the item you want to be selected by default.
- Mark the selected checkbox to set selected by default.
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
}
}
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.