3

I'm trying to write an extension, to change UIControl components font size

extension UIViewController {

func changeFontSize(){
    for v in self.view.subviews{
        var fontSize = CGFloat(10)
        if let V = v as? UIButton       {V.titleLabel?.font = V.titleLabel?.font.withSize(fontSize)}
        if let V = v as? UILabel        {V.font = V.font.withSize(fontSize)}
        if let V = v as? UITextField    {V.font = V.font?.withSize(fontSize)}
    }
}

My problem is with some components like UITableView , how can I access the cells elements, and the UITableView Section header components so that I make the extension also change all subviews of all types texts fonts ?

Lukas Würzburger
  • 6,543
  • 7
  • 41
  • 75
DeyaEldeen
  • 10,847
  • 10
  • 42
  • 75

2 Answers2

6

You need a recursive implementation so that you go into the subviews of any views. And your extension should be on UIView, not UIViewController.

extension UIView {
    func changeFontSize(){
        let fontSize = CGFloat(10)
        if let v = self as? UIButton {
            v.titleLabel?.font = v.titleLabel?.font.withSize(fontSize)
        } else if let v = self as? UILabel {
            v.font = v.font.withSize(fontSize)
        } else if let v = self as? UITextField {
            v.font = v.font?.withSize(fontSize)
        } else {
            for v in subviews {
                v.changeFontSize()
            }
        }
    }
}

If you wish to call this on a view controller, simple do:

someViewController.view.changeFontSize()
rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

Another common option is to use UIAppearance

And since UIButtons use UILabel as a subview, it would work there too.

extension UILabel {
    var defaultFont: UIFont? {
        get { return self.font }
        set { self.font = newValue }
    }
}


UILabel.appearance().defaultFont = UIFont.systemFont(ofSize: 25)

Repeat for UITextField and other controls.

Adapted from https://stackoverflow.com/a/36324142/127422

See also NSHipster's post on UIAppearance

Jon Willis
  • 6,993
  • 4
  • 43
  • 51