Reusable UILabel styles in Swift, Xcode 6.4

1.6k Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

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