Reputation: 273
I have four segments in my UISegmentedControl. I am trying to programmatically set the selected state of the third and fourth segments at the same time if the user has selected the first segment.
Example: In a given segmented control, if the user selected segment A, then C, D should be selected.
I looked into Apple's methods but found none that match my requirement. I am looking for a method that would look like-
Any help on this is much appreciated.
-(void) setSelected: (BOOL) selected forSegmentAtIndex: (NSUInteger) segment
Parameters
enabled
YES to select the specified segment or NO to unselect the segment. By default, segments are unselected.
segment
An index number identifying a segment in the control. It must be a number between 0 and the number of segments (numberOfSegments) minus 1; values exceeding this upper range are pinned to it.
Upvotes: 6
Views: 28869
Reputation: 1873
First, create an outlet from the segmented control you've added from the UI
@IBOutlet weak var segmentedControl: UISegmentedControl!
Using the code below programmatically change the selected segment
segmentedControl.selectedSegmentIndex = 1 // index
Upvotes: 2
Reputation: 4375
This code is for swift 2.0
// Declare outlet for our segmented control
@IBOutlet weak var segmentcontroll: UISegmentedControl!
// Declare our IBAction for the segmented control
@IBAction func segmentneeded(sender: AnyObject) {
// Here we test for the presently selected segment
switch segmentcontroll.selectedSegmentIndex {
case 0:
self.view.backgroundColor=UIColor.purpleColor()
segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
case 1:
self.view.backgroundColor=UIColor.yellowColor()
segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
default:
self.view.backgroundColor=UIColor.grayColor()
segmentcontroll.selectedSegmentIndex=UISegmentedControlNoSegment
}
}
Upvotes: 4
Reputation: 1918
Programmatically this can not be done in SegmentControl but you can do this way: You can create one imageView put four button on that which size are equal like segments and make them transparent when on one button is pressed change the image of imageView which look like Segment C, D are pressed this way you can do other task.
Upvotes: 0
Reputation: 34829
The UISegmentedControl
works like a set of radio buttons. That is, only one segment can be selected at a time. To get the functionality that you want, you will need to make a custom control that looks like a UISegmentedControl
.
Upvotes: 2
Reputation: 3763
Use setSelectedSegmentIndex
like so -
[mySegmentControl setSelectedSegmentIndex:index]
Upvotes: 7
Reputation: 17687
You can simply use selectedSegmentIndex
property as there is int he documentation
So simply:
[segmentControl setSelectedSegmentIndex:2];
Consider that you can set just 1 index and that if you want unselect all you have to set the index -1.
Upvotes: 0