我想通过代码设置UIButton的标题。我发现自己不得不为UIControlStateNormal,UIControlStateHighlighted,UIControlStateDisabled,UIControlStateSelected调用 - [UIButton setTitle:forState:]。而且这甚至没有考虑到这些状态的所有组合。
毋庸置疑,这很无聊。我可以进行一次调用,将一个字符串设置为所有状态的标题吗? (因为,我认为在95%的情况下,这是理想的行为?)
答案 0 :(得分:9)
是的,你当然可以。 From the docs:
一般情况下,如果属性不是 为状态指定,默认为 使用
UIControlStateNormal
值。 如果UIControlStateNormal
的值 未设置,则属性默认 到系统值。因此,在 最小值,你应该设置值 正常状态。
所以只需设置UIControlStateNormal
的标题,你就是黄金。
答案 1 :(得分:7)
[button setTitle:@"Title" forState:UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected]
如果你想简明扼要:
#define kAllControlStates (UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected)
[button setTitle:@"Title" forState:kAllControlStates];
简洁而不透明:
[button setTitle:@"Title" forState:0xffff];
更新:我应该在回答之前对此进行测试。事实证明,像UIControlStateHighlighted|UIControlStateDisabled
这样的掩码表示控件突出显示和时的状态。我错误地认为该掩码表示“高亮或已禁用”。总而言之,你最好先了解Frog先生的答案。
答案 2 :(得分:0)
为UIButton创建一个类别方法,一次为所有状态设置它。
答案 3 :(得分:0)
尽管99%的时间都回到了UIControlStateNormal状态的值可能已经足够好了,但我已经为1%的用例提出了解决这个问题的方法。 (我在子类中有应用程序定义的状态,这意味着回退到正常状态是不正确的。)
我在这里发布它是为了完整性,即使答案已被接受。基本上它设置状态的属性加上您指定的各个附加状态的每个组合。
@interface UIButton (AdditionalStates)
- (void)setTitle:(NSString *)title forState:(UIControlState)state additionalStates:(UIControlState)additionalStates;
@end
@implementation UIButton (AdditionalStates)
- (void)setTitle:(NSString *)title forState:(UIControlState)state additionalStates:(UIControlState)additionalStates
{
[self setValue:title forKey:@"title" state:state additionalStates:additionalStates mask:(1 << 0)];
}
- (void)setValue:(id)value forKey:(NSString *)key state:(UIControlState)state additionalStates:(UIControlState)additionalStates mask:(NSUInteger)mask(UIControlState)additionalStates
{
if (additionalStates == 0) {
[self setValue:value forKey:key state:state];
return;
}
// Iterate over each 'on' bit in additionalStates, starting from the mask bit
while (mask > 0) {
if (additionalStates & mask) {
// Delete the current bit from additionalStates
NSUInteger reducedAdditionalStates = (additionalStates ^ mask);
// Set the title for combinations of the remaining additional states with and without the mask bit
[self setValue:value forKey:key state:(state | (additionalStates & mask)) additionalStates:reducedAdditionalStates mask:(mask << 1)];
[self setValue:value forKey:key state:state additionalStates:reducedAdditionalStates mask:(mask << 1)];
}
mask = (mask << 1);
}
}
- (void)setValue:(id)value forKey:(NSString *)key state:(UIControlState)state
{
if ([key isEqualToString:@"title"]) {
[self setTitle:value forState:state];
return;
}
}
@end