如何使用 Objective-C 更改多个 UIButton 颜色

How to change multiple UIButton colors with Objective-C

我使用了很多按钮,我想要一种有效的方法来更改所有背景颜色,而不是一个一个地更改它或在 AppDelegate 上进行更改。

我基本上想避免这种情况

  buttonOne.backgroundColor = [UIColor BlueColor];
  buttonTwo.backgroundColor = [UIColor BlueColor];
  buttonThree.backgroundColor = [UIColor BlueColor];
  buttonFour.backgroundColor = [UIColor BlueColor];

如果不在 AppDelegate 中执行此操作,有什么有效的方法。

你可以这样做:

UIColor *color = [UIColor blueColor];
NSArray *buttons = @[buttonOne, buttonTwo, buttonThree, buttonFour];
for(UIButton *button in buttons) {
   button. backgroundColor = color;
}

或者,更酷的方法,使用 KVC:

NSArray *buttons = @[buttonOne, buttonTwo, buttonThree, buttonFour];
[buttons setValue:[UIColor blueColor] forKey:@"backgroundColor"];

试试这个,你可以改变控件的外观代理。

[[UIButton appearance] setBackgroundColor:[UIColor blueColor]];

在 Appdelegate 中写这个 didFinishLaunchingWithOptions

希望这对您有所帮助。

谢谢。

如果您的所有按钮都是同一视图的子视图,并且您希望更改该子视图中的所有按钮,您可以执行如下操作:

UIColor *color = [UIColor blueColor];
for (UIView *view in self.view.subviews) {
    if ([view isKindOfClass:[UIButton class]]) {
        ((UIButton*)view).backgroundColor = color;
    }
}

另一个选项(如果您不想更改给定视图中的所有按钮特别有用)是为每个按钮设置相同的标签,然后更改子视图的背景颜色(如果有)有那个特定的标签:

UIColor *color = [UIColor blueColor];
for (UIView *view in self.view.subviews) {
    if (view.tag == 1000) {
        ((UIButton*)view).backgroundColor = color;
    }
}

同样,您可以将每个按钮设置为具有一个连续数字顺序的唯一标签,然后像这样遍历每个按钮:

UIColor *color = [UIColor blueColor];
for (int i = 1 ; i <= 10 ; i ++) { // <-- Changing buttons with tags 1 - 10
    ((UIButton*)[self.view viewWithTag:i]).backgroundColor = color;
}