How to Set Selected Segment Index in Uisegmentedcontrol

How to set selected segment index in UISegmentedControl?

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

Change UISegmentedControl selected index or value programmatically

Change in viewDidLoad:

[seg setSelectedSegmentIndex:index];

you change use the index value as your wish.

Change selected segment of UISegmentedControl

After you change view controller and you come back the viewDidLoad method called again thats why you are seeing the default selected index. The way to overcome this is store the selected the selected index into some app delegate property or you can create singleton class for the better design to preserve the state .And in your viewDidLoadMethod .

-viewDidLoad
{
AppDelegate *delegate=[[UIApplication sharedAppliection]delegate];
[_Segment setSelectedSegmentIndex:delegate.selectedIndex];
}

This wil work for you .

How do I switch UISegmentedControl programmatically?

The selectedSegmentIndex property identifies the selected segment of a UISegmentedControl. Set this property to the any valid segment index, or UISegmentedControlNoSegment (-1) to turn off the current selection.

// select the first segment
segmented.selectedSegmentIndex = 0;

// turn off the current selection
segmented.selectedSegmentIndex = UISegmentedControlNoSegment;

how to save the index and title of a segmented control in core data

Create a enum for every SegmentedControls with CaseIterable

enum Planet: String, CustomStringConvertible, CaseIterable {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
var description: String {
return self.rawValue.capitalized
}
}

And use the Planet.allCases array to create the segments for the segmented control

let segmentedControl = UISegmentedControl(items: Planet.allCases)

or

Planet.allCases.enumerated().forEach {
segmentedControl.insertSegment(withTitle: $1, at: $0, animated: true)
}

When selection changed in the segment control save the selected index in core data.

@objc func indexChanged(_ sender: UISegmentedControl) {
print(Planet.allCases[sender.selectedSegmentIndex])
//save sender.selectedSegmentIndex in core data
}

When you want to display the selected titles in a different view, get selected indexes from core data. And get the corresponding string value from the Enum.allCases array

let selectedPlanetIndex = 5//Index fetched from core data
let selectedPlanetTitle = Planet.allCases[selectedPlanetIndex]//saturn

How can I set the default state of a UISegmentedControl?

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



Related Topics



Leave a reply



Submit