单击更改多个UIButton的背景颜色

时间:2022-01-26 20:31:10

I have 16 UIButton in a UIViewController and only one need to be selected at a time.

我在UIViewController中有16个UIButton,一次只需要选择一个。

I have created a UIButton collection and changing backgroundColor by performing the for loop. It's working fine.

我已经创建了一个UIButton集合并通过执行for循环来更改backgroundColor。它工作正常。

But I need a quick solution in one / two line or I can say the efficient way to change color in a single click.

但是我需要一两行的快速解决方案,或者我可以说一次点击改变颜色的有效方法。

I don't think my way is efficient because what if the UIViewController has 50 UIButton.

我不认为我的方式是有效的,因为如果UIViewController有50个UIButton。

P.S. Don't tell me to take UICollectionView as I can easily do with that!

附:不要告诉我采取UICollectionView,因为我可以轻松地做到这一点!

1 个解决方案

#1


1  

You will anyway need enumerate your buttons. But you can do this once in extension:

你无论如何都需要枚举你的按钮。但你可以在扩展中执行一次:

extension Array where Element: UIButton {
    func setBackgroundColor(color: UIColor) {
        for element in self {
            element.backgroundColor = color
        }
    }
}

#1


1  

You will anyway need enumerate your buttons. But you can do this once in extension:

你无论如何都需要枚举你的按钮。但你可以在扩展中执行一次:

extension Array where Element: UIButton {
    func setBackgroundColor(color: UIColor) {
        for element in self {
            element.backgroundColor = color
        }
    }
}