3

I have mainStack as a UIStackView. This stack contains 4 UIStackViews. Each of these two 4 stacks contain 2 buttons. I am trying to locate these buttons by enumeration, using this code:

// get the subviews of the main stack
let subviews = mainStack!.arrangedSubviews as Array

// enumerate each one
for subStack in subviews as UIStackView { // 1
  let buttons = subStack.subvies

}

I have an error on //1 with the message:

Cannot convert value of type '[UIView]' to type 'UIStackView' in coercion

Why is that? The subviews of the main stack are UIStackViews.are

any ideas?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Duck
  • 34,902
  • 47
  • 248
  • 470
  • 1
    Why are you even using NSArray instead of Swift array? – PGDev Jul 01 '19 at 11:50
  • 1
    Oooops, sorry about that. 11 years using objective C. I have corrected the code but te problem persists with a different message now. – Duck Jul 01 '19 at 11:52

2 Answers2

4

"The subviews of the main stack are UIStackViews"

The stackview may contain other UI elements also. You can use pattern matching with the for loop like this

for case let stackView as UIStackView in mainStackView.arrangedSubviews  {
    for case let button as UIButton in stackView.arrangedSubviews {
        button.addTarget...
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
3

Why Error?

for subStack in subviews as UIStackView 

In the above line of code, subviews is an Array and you're trying to parse it to UIStackView. That's the reason it is giving compiler error.

Solution:

You can simply do like,

if let subviews = mainStack?.arrangedSubviews as? [UIStackView] {
    subviews.forEach { (subStack) in
        let buttons = subStack.arrangedSubviews as? [UIButton]
        //add your code here...
    }
}

Note: Use if-let to unwrap optionals instead of force unwrapping(!) them.

RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
PGDev
  • 23,751
  • 6
  • 34
  • 88