eifersucht
eifersucht

Reputation: 691

How to refer al subview hierarchy in swift

Hello I'm trying to apply some styles to IBOutlets from Swift 3 code. But when I'm trying to refer the IBOutlet from my code, only works if I add the immediatelly superior UIView as IBOutlet.

For example (adding font style to all label elements inside View):

Declaration

@IBOutlet var exampleView: UIView!

Inside ViewDidLoad() func

for case let label as UILabel in exampleView.subviews {
            label.font = UIFont(name: "myfont-name", size: 13.0)
}

In this case the label is a immediate child of the exampleView and this works fine. But I want to do more general code for dynamic font type change in my app.

When I try to refer to self.view.subviews for loop all the labels no mather hierarchy depth the code don't work.

Example:

for case let label as UILabel in self.view.subviews {
            label.font = UIFont(name: "myfont-name", size: 13.0)
}

Upvotes: 2

Views: 343

Answers (1)

Akhilrajtr
Akhilrajtr

Reputation: 5182

use recursion for this

func setFontToSubviews(view:UIView, font: UIFont) {
    for subview in view.subviews {
        if let label = subview as? UILabel {
             label.font = font
        }
        setFontToSubviews(view:subview, font:font)
    }
}

and invoke this method with required view and font.

Upvotes: 5

Related Questions