如何在 iOS 中以编程方式更改 UIButton 中的 textLabel 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11135532/
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
How to Change textLabel property in UIButton programmatically in iOS?
提问by Ohad Regev
I have a UIButton
that should have 2 statuses - "Play" and "Pause"; i.e. - at the first time the user sees it it says "Play" and then whenever the user clicks it it should switch between "Play" and "Pause".
我有一个UIButton
应该有 2 个状态 - “播放”和“暂停”;即 - 在用户第一次看到它时,它说“播放”,然后每当用户点击它时,它应该在“播放”和“暂停”之间切换。
I managed to create the controller itself - the content is played and paused properly - but I cannot seem to change the UIButton Text Label text.
我设法自己创建了控制器 - 内容已正确播放和暂停 - 但我似乎无法更改 UIButton 文本标签文本。
I use:
我用:
myButton.titleLabel.text = @"Play";
myButton.titleLabel.text = @"Pause";
It's not working. The text is not changing. I also tried [myButton.titleLabel setText:@"Pause"] and it's not working as well.
它不起作用。文字没有变化。我也试过 [myButton.titleLabel setText:@"Pause"] 并且效果不佳。
How can I set it?
我该如何设置?
回答by Rui Peres
It should be:
它应该是:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
You need to pass the state
as well. You can check other state
's here.
你也需要通过state
。你可以在这里查看其他state
人的。
You can then do something like this:
然后你可以做这样的事情:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Stop" forState:UIControlStateSelected];
回答by Wissa
SWIFT 4
快速 4
myButton.setTitle("Pause", for: .normal)
回答by LostInTheTrees
I found this to be somewhat out of date since attributed strings were added. Apparently titles of buttons assigned in a storyboard are attributed strings. Attributed titles take precedence over NSString titles, so if you want to use a simple string as a title you have to remove the attributed title first. I did as below, though there may be a better way. You could, of course, make your new title also an attributed string.
我发现这有点过时了,因为添加了属性字符串。显然,故事板中分配的按钮标题是属性字符串。属性标题优先于 NSString 标题,因此如果您想使用简单字符串作为标题,则必须先删除属性标题。我做了如下,虽然可能有更好的方法。当然,您可以将新标题也设为属性字符串。
[myButton setAttributedTitle: nil forState: 0xffff];
[myButton setTitle: @"Play" forState: UIControlStateNormal];
回答by Aviram Netanel
And if you want to load it on page load, and support localized language:
如果您想在页面加载时加载它,并支持本地化语言:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.flagToChangeLabel){
NSString* newBtnTitle = NSLocalizedString(@"LOCALIZED_KEY", nil);
[self.laterButton setTitle:newBtnTitle forState:UIControlStateNormal];
[self.laterButton setTitle:newBtnTitle forState:UIControlStateSelected];
}
}