我的应用程序中的所有标签都使用设置了间距/字距调整值以及颜色和其他一些东西的字体,我想看看应用了所有这些属性后 Storyboard中的东西是什么样子。
由于 UILabel 是一个 UIView,我希望可以通过使用 @IBDesignable 来实现这一点。但经过一些实验后,我无法在 Storyboard 中发生任何事情。
这是代码:
@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"
但在 Storyboard 中,标签显示时未应用任何属性字符串设置。
有谁知道我正在尝试的事情是否可行,如果可行,如何让它发挥作用?
最佳答案
swift 3
根据您的情况,使用 @IBInspectable 来覆盖 UILabel 的文本变量,这将允许您从属性检查器传递文本(见屏幕截图)将在 Storyboard 上呈现
@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
}
}
关于ios - 是否可以使用@IBDesignable 在 Storyboard中显示 UILabel.attributedText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902356/