[英]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. 由于UILabel是UIView,我希望可以通过使用@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? 有人知道我正在尝试的事情是否可能吗?如果可以,如何使它正常工作?
Swift 3 迅捷3
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 根据您的情况,使用@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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.