有没有办法在 UIButton 上 setTitle 一次更新所有 UIControlStates ?
我有一个 UIButton,我想更新它的标题,但我不想总是为每个状态执行此操作,如下所示:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Play" forState:UIControlStateHighlighted];
[myButton setTitle:@"Play" forState:UIControlStateSelected];
有更好的方法吗?
I have a UIButton, and I'd like to update its title, but I'd rather not have to always do it for each and every state like the following:
[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Play" forState:UIControlStateHighlighted];
[myButton setTitle:@"Play" forState:UIControlStateSelected];
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据文档,您只需要调用:
In Objective-C:
In Swift:
UIButton 文档解释了原因:
也就是说,如果您只设置正常值,其他状态在设置时将引用它。
According to the documentation you should only need to call:
In Objective-C:
In Swift:
The UIButton docs explain why:
Namely, that if you only set the normal value the other states will refer to it when being set.
或者您可以通过以下方式设置标题:
or you can setTitle by :
您可以为 UIButton 创建一个类别:
You can create a category for UIButton:
2019年
只是
2019
It's just
答案:
or
一般来说是不正确的,因为它仅在尚未设置某些状态的标题时才有效。例如:
在此代码之后按钮仍然具有标题“HL”以突出显示状态。
因此,要在一般情况下更改所有使用状态的标题,您必须循环遍历所有这些状态:(
如果您使用其他状态,例如 .disabled,您也必须将它们的组合添加到循环中)
注意 : UIControl.State 是一组选项,因此设置标题时:
不会为选定状态和突出显示状态设置标题“全部”,而是为选定和突出显示的组合状态设置标题“全部” 同时。
The answer:
or
is not correct in general, because it works only if the title for some state is not already set. For example:
After this code button still have title "HL" for highlighted state.
So to change title for all used states in general case, you have to loop through all these states:
(If you use other states e.g. .disabled, you have to add they combinations to loop as well)
Note: UIControl.State is a Set of options, so setting the title with:
does not set title "All" for both selected and highlighted states, instead it sets the title "All" for the combined state which is selected and highlighted at the same time.