2

Is there an easier way of styling UILabels than making custom classes that override UILabel. Currently I have need of a bunch of styles with different font sizes and text colors.

user1354603
  • 4,034
  • 4
  • 31
  • 43
  • What's wrong with setting the `font` and `textColor` attributes on a standard `UILabel`? – hennes Aug 13 '15 at 13:12
  • Do you mean individually on each and every UILabel by using the interface builder? – user1354603 Aug 13 '15 at 13:15
  • Well, your question doesn't mention IB. These properties obviously need to be applied in code. Alternatively you could try the `UIAppearance` protocol. It is, however, limited in Swift. – hennes Aug 13 '15 at 13:39

1 Answers1

5

I don't know this is a good practice... but you could something like:

extension UILabel {
    @IBInspectable var myStyle: String {
        set {
            switch newValue  {
            case "style1":
                self.font = UIFont.systemFontOfSize(17)
                self.textColor = UIColor.blackColor()

            case "style2":
                self.font = UIFont.boldSystemFontOfSize(32)
                self.textColor = UIColor.redColor()

            default:
                break
            }
        }
        get {
            return ""
        }
    }
}

screenshot


Maybe, you should define a subclass with @IBDesignable. Because that shows much better preview in the IB. And, you can use Editor > Size To Fit or Auto Layout feature in IB.

@IBDesignable class StyledLabel: UILabel {
    @IBInspectable var myStyle: String = "" {
        didSet {
            switch self.myStyle {
            case "style1":
                self.font = UIFont.systemFontOfSize(17)
                self.textColor = UIColor.blackColor()
            case "style2":
                self.font = UIFont.boldSystemFontOfSize(32)
                self.textColor = UIColor.redColor()
            default:
                break
            }
        }
    }
}

screenshot

rintaro
  • 51,423
  • 14
  • 131
  • 139
  • This is exactly what I was looking for! Now I just need to know if it is good practice or not – user1354603 Aug 13 '15 at 13:54
  • The whole point of this question was to avoid using custom classes because I wanted to avoid setting the custom classes for all my UILabels :).. Preview is less important than writing less code so for now I'll stick to what you wrote before the edit – user1354603 Aug 13 '15 at 14:55
  • Second option (making a class) I tested and is really great. Now I can just change the class name of my custom UI and style as I want. Really helpful. – Touhid Nov 04 '20 at 06:23