ios 以编程方式 UISegmentedControl 文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9815059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UISegmentedControl text programmatically
提问by user1015777
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.
我使用界面构建器(来自故事板)创建了一个带有两个段的 UISegmentedControl,但我想以编程方式设置两个段的文本。我想这样做是因为我将 NSLocalizedString 用于所有按钮、标签、标题等。我在界面构建器中创建所有内容,然后以编程方式添加文本。我设法使每个项目都以这种方式工作,但我找不到向 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
非常感谢
回答by shabbirv
[segmentedControl setTitle:<YourLocalizedString> forSegmentAtIndex:0];
回答by Kevin Singh
The correct answer for people using SWIFT 4would be
使用SWIFT 4 的人的正确答案是
segmentedControl.setTitle("Your Title", forSegmentAt: 0)
回答by Obliquely
Use setTitle:forSegmentAtIndex:to assign the title to your segments of the segmented control.
使用setTitle:forSegmentAtIndex:将标题分配给分段控件的段。
Hope this would help you.
希望这会帮助你。
回答by Kiran jadhav
Updated :
更新 :
Use below simple code to set UISegmentControl title programatically;
使用以下简单代码以编程方式设置 UISegmentControl 标题;
//.h file:
//.h文件:
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;
// .m file:
// .m 文件:
- (void)viewDidLoad {
[super viewDidLoad];
[self.segmentControl setTitle:@"Love It" forSegmentAtIndex:0];
[self.segmentControl setTitle:@"Hate It" forSegmentAtIndex:1];
[self.segmentControl setTitle:@"Ehh" forSegmentAtIndex:2];
}