1

I need to change the font of all the UILables, UITextViews, UITextFields, UIButtons (title), in the app based on the content of the text or title. How can I do this globally?.

I did try​ to create an extension for each and make the changes in layoutSubviews(), but this only worked for UILabels.

extension UILabel {

override open func layoutSubviews() {
    super.layoutSubviews()

    let text = self.text ?? ""
    var fontName = THEME_FONT_NAME

    if (!text.isAlphanumeric) {
        self.font = UIFont.systemFont(ofSize: self.font.pointSize, weight: fontWeight)
        return
    }

    self.font = UIFont(name: fontName, size: self.font.pointSize)
}}
hashB
  • 113
  • 1
  • 12
  • 3
    provide your trial code – Sagar Bhut Aug 06 '19 at 07:27
  • so, what hurdle you facing, its like if textfield.text == "your text expected" { //set textfield font here } What issue you facing doing so – Chatar Veer Suthar Aug 06 '19 at 07:39
  • https://stackoverflow.com/questions/32570745/detect-uilabel-text-change-in-swift is for label change, probably works for uitexrtview, uitextfield also.. https://stackoverflow.com/questions/38989264/swift-determine-if-the-buttons-title-was-changed is for buttons – Vollan Aug 06 '19 at 07:42
  • @Vollan I don't want to create a subclass. As we already have so many labels in the app and it's hard to add a subclass for all. Is there anyway we could do this in an extension – hashB Aug 06 '19 at 08:17
  • In that case you have to setup a listener at some stage of your uilabel, textview, tefxtfield etc. and then setup a listener https://stackoverflow.com/a/14327575/4757272 so for each scenario you have to `theView.setupListener()` – Vollan Aug 06 '19 at 08:29

1 Answers1

0

Are you using firebase, then specify fonts in remote config. fetch those fonts and create some utility class with static property font. e.g

class Utils{
var font: UIFont = UIFont("fontFetched") ?? default font
}

like: label.text.font = font

and use it wherever you implement fields and buttons

Rajesh Budhiraja
  • 192
  • 1
  • 12