Skip to content
This repository has been archived by the owner on Sep 17, 2022. It is now read-only.

Setting up an @IBDesignable Label

Beat edited this page Jun 25, 2016 · 4 revisions

To set up an @IBDesignable label using Typesetter, you will need a font definition enum. If you are using custom fonts, make sure you added them to your Info.plist under the key Fonts provided by application.

Note that in the setup below, the rawValue's of the enum are not mapped to the font name, which allows you to specify a more concise string in interface builder, which will then be mapped via the name attribute to the right font name.

import Typesetter

enum MyFont: String, TypesetterFont {
   case Regular
   case Bold

   var name: String {
       switch self {
       case .Regular:
           return "Georgia"
       case .Bold:
           return "Georgia-Bold"
       }
   }
}

In your label, assign the text styles and font rawValue's to @IBInspectable variables. Interface builder does not yet support enums, so the mapping from string to enum is done in setupLabel

import Typesetter

@IBDesignable class MyLabel: UILabel {
    
    private let typesetter = Typesetter(bundle: NSBundle(forClass: MyLabel.self))
    
    @IBInspectable var textStyle: String = TypesetterTextStyle.Body.rawValue {
        didSet {
            setupLabel()
        }
    }

    @IBInspectable var fontName: String = MyFont.Regular.rawValue {
        didSet {
            setupLabel()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLabel()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupLabel()
    }
    
    private func setupLabel() {
        guard let font = MyFont(rawValue: fontName) else { return }
        self.font = typesetter.sizedFontFor(textStyle, font: font)
    }

}
Clone this wiki locally