是否可以使用@IBDesignable在故事板中显示UILabel.attributedText?

时间:2016-12-01 03:53:49

标签: ios swift xcode storyboard

我的应用中的所有标签都使用了设置了间距/字距调整值的字体以及颜色和其他一些内容,我想看看故事板中应用了所有这些属性的内容。

由于UILabel是UIView,我希望通过使用@IBDesignable来实现这一目标。但经过一些实验,我无法在故事板中发生任何事情。

这是代码:

@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"

但在故事板中,标签显示时未应用任何属性字符串设置。

是否有人知道我正在尝试的是否可行,如果是,如何使其正常工作?

1 个答案:

答案 0 :(得分:6)

Swift 3

根据您的情况,使用 @IBInspectable 覆盖 UILabel 的文本var ,这将允许您从属性检查器传递文本(看屏幕截图)将在故事板上呈现

enter image description here

@IBDesignable class DGlabel: UILabel {

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

@IBInspectable var fontSize: CFloat = 15 {
    didSet {
        decorate()
    }
}


@IBInspectable var fontColor: UIColor = UIColor.red {
    didSet {
        decorate()
    }
}

/*** more inspectable var can be added **/

func decorate() {

    guard let text = text else { return }

    let titleAttributes = [
        NSFontAttributeName : UIFont.systemFont(ofSize: fontSize),
        NSForegroundColorAttributeName : fontColor,
        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
    }
}
相关问题