Reputation: 83
I am trying to do a loop to iterate through all UIButtons found on the view in order to change the position of each button. (See code below)
for case let button as UIButton in self.view.subviews {
rect = button.frame
rect.origin.x = rect.origin.x + 20
rect.origin.y = rect.origin.y + 20
button.frame = rect
}
However, when I debugged the code I found that the loop is not finding any buttons, and thus the positions remained the same. I have 9 buttons in a View found in the View Controller.
Anyone knows what's wrong with this loop?
Upvotes: 2
Views: 1264
Reputation: 19602
Your code is working. This:
var view = UIView()
view.addSubview(UIView())
view.addSubview(UIButton())
for case let button as UIButton in view.subviews {
print(button)
}
prints:
<UIButton: 0x7fcc9bd07320; frame = (0 0; 0 0); opaque = NO; layer = <CALayer: 0x60000002dca0>>
Conclusion: self.view.subviews does not contain any UIButtons
.
Upvotes: 0
Reputation: 534885
Your code works fine for me. The implication is that your buttons are not subviews of self.view
, but subviews of some view further down the hierarchy. You will have to write a recursive version of your loop.
For example:
func lookForButton(_ v: UIView) {
let subs = v.subviews
if subs.count == 0 {return}
for vv in subs {
if vv is UIButton {
print(vv) // just testing: do your real stuff here
}
lookForButton(vv)
}
}
lookForButton(self.view)
Upvotes: 4