Seong Lee Seong Lee - 7 months ago 12
Swift Question

How to check backgroundColor of all buttons

I want to be able to check if all buttons' background color is UIColor.whiteColor. I'm determining whether a view is in search mode or in normal mode by the button state.

I want to do something similar with the following but

contains()
checks if array contains certain value. It wouldn't work in my case because
UIColor.whiteColor
is a property of UIButton.

if contains(categoryScrollView.subviews, UIColor.whiteColor) {
inSearchMode = false
}


Then if I put it in the following way, I do not know how I can make sure all button's background color is white as it will pass validation as soon as any button's background color is white which is not what I need.

for button in categoryScrollView.subviews {

if button.backgroundColor == UIColor.whiteColor() {
inSearchMode = false
}
}


How can I check is background color of all buttons?

Answer

I'd enclose this check in a function, like this (note that I'm including a check that each view is a button):

func allWhiteButtons(view: UIView)-> Bool{
  for view in view.subViews {
    if let button = view as? UIButton {
      if button.backgroundColor != UIColor.whiteColor() {
        return false
      }
    }
  }
  return true
}