Essence of chicken Essence of chicken - 3 days ago 6
Swift Question

Is it possible to display UILabel.attributedText in a storyboard using @IBDesignable?

All the labels in my app are using fonts with spacing/kerning values set as well as colors and several other things and I want to see what thing look like in the storyboard with all of these attributes applied.

As UILabel is a UIView I was hoping it might be possible to achieve this by using @IBDesignable. But after some experimentation I can't get anything to happen in the storyboard.

This is the code:

@IBDesignable class CustomLabel: UILabel {
@IBDesignable override var text: String? {
didSet {
guard let text = text else { return }
let titleAttributes = [NSForegroundColorAttributeName: UIColor.green]
let titleString = NSMutableAttributedString(string: text, attributes: titleAttributes)
titleString.addAttribute(NSKernAttributeName, value: 5, range: NSRange(location: 0, length: text.characters.count))
// Other attributes
self.attributedText = titleString
}
}
}


...

@IBOutlet weak var theTitle: CustomLabel!
theTitle.text = "Some stuff"


But in the storyboard the label is displayed without any of the attributed string settings applied.

Does anybody know if what I'm attempting is going to be possible, and if so how to get it working?

dip dip
Answer

As per Your situation use @IBInspectable to overridden text var of UILabel , This will allow you to pass the text from property inspector (see screen shot) which will be rendered on Storyboard

enter image description here

@IBDesignable class DGlabel: UILabel {

@IBInspectable override var text: String? {
    didSet {
      decorate()
    }
}

func decorate() {

    guard let text = text else { return }

    let titleAttributes = [
        NSFontAttributeName : UIFont.systemFont(ofSize: 15.0),
        NSForegroundColorAttributeName : UIColor.green,
        NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue
        ] as [String : Any]

    let titleString = NSMutableAttributedString(string: text, attributes: titleAttributes)

     // Other attributes
    titleString.addAttribute(NSKernAttributeName, value: 5, range: NSRange(location: 0, length: text.characters.count))

    self.attributedText = titleString
}

}

Comments