我有一些UIButton
s,我正在以编程方式在其上设置自定义字体,如下所示:
Button1.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button2.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button3.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button4.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button5.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
Button6.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
这段代码是正确的并且有效,但它似乎不是最简单的编写方式。有没有办法循环使用这些元素?
我想象过这样的事情:
for (int i = 1; i <= 5; i++) {
Button(i).titleLabel.font = etc.. // How would I get the value of 'i'?
}
或者这只是一个坏主意?
答案 0 :(得分:5)
您可以使用NSArray迭代:
UIFont *font = [UIFont fontWithName:@"myCustomFont" size:16];
NSArray *buttons = [NSArray arrayWithObjects: Button1, Button2, Button3,
Button4, Button5, Button6,
nil];
for (UIButton *button in buttons) {
button.titleLabel.font = font;
}
答案 1 :(得分:2)
NSMutableArray *buttons = [NSMutableArray array];
[buttons addObject: Button1];
[buttons addObject: Button2];
[buttons addObject: Button3];
[buttons addObject: Button4];
[buttons addObject: Button5];
[buttons addObject: Button6];
for (UIButton *button in buttons) {
button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}
或
for (int i=1;i<7;i++) {
SEL selector = selectorFromString([NSString stringWithFormat:@"Button%d", i]);
UIButton *button = [self performSelector:selector];
button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}
答案 2 :(得分:1)
好吧,我想你可以将所有按钮放在一个数组中,然后通过它快速枚举。
NSArray *buttons;
//Put all of your buttons inhere
for (UIButton *button in buttons)
{
button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}
答案 3 :(得分:0)
这个怎么样? currentView是包含所有按钮的UIView。
NSArray* buttonsArray = currentView.subviews;
for((UIButton*) button in buttonsArray)
{
button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}