UISegmentedControl text programmatically

IphoneObjective CIosIpad

Iphone Problem Overview


I have created a UISegmentedControl with two segments using the interface builder (from storyboard), but I would like to set the text of the two segments programmatically. I want to do this because I am using NSLocalizedString for all of my buttons, labels, titles etc. I create all the stuff in interface builder and then I add text programmatically. I have manage to make every item to work that way but I cannot find a way to add text to my UISegmentedControl.

Is there any way to do that? I ma trying to use the following but because the segmented control is already created in the interface builder it does not work.

[segmentedControl initWithItems:[NSArray arrayWithObjects:NSLocalizedString(@"Title 1", @"Title 1"),NSLocalizedString(@"Title 2", @"Title 2"), nil]];

Thanks a lot

Iphone Solutions


Solution 1 - Iphone

[segmentedControl setTitle:<YourLocalizedString> forSegmentAtIndex:0];

Solution 2 - Iphone

The correct answer for people using SWIFT 4 would be

segmentedControl.setTitle("Your Title", forSegmentAt: 0)

Solution 3 - Iphone

Use setTitle:forSegmentAtIndex: to assign the title to your segments of the segmented control.

Hope this would help you.

Solution 4 - Iphone

> Updated :

Use below simple code to set UISegmentControl title programatically;

//.h file:

@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;

// .m file:

- (void)viewDidLoad {

    [super viewDidLoad];

     [self.segmentControl setTitle:@"Love It" forSegmentAtIndex:0];
     [self.segmentControl setTitle:@"Hate It" forSegmentAtIndex:1];        
     [self.segmentControl setTitle:@"Ehh" forSegmentAtIndex:2];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1015777View Question on Stackoverflow
Solution 1 - IphoneshabbirvView Answer on Stackoverflow
Solution 2 - IphoneKevin SinghView Answer on Stackoverflow
Solution 3 - IphoneObliquelyView Answer on Stackoverflow
Solution 4 - IphoneKiran JadhavView Answer on Stackoverflow