![](/img/trans.png)
[英]Make link in UILabel.attributedText *not* blue and *not* underlined
[英]Is it possible to display UILabel.attributedText in a storyboard using @IBDesignable?
我的应用程序中的所有标签都使用设置了间距/字距值以及颜色和其他几种设置的字体,我想看看应用了所有这些属性的情节提要中的外观。
由于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"
但是在情节提要中将显示标签,而未应用任何属性字符串设置。
有人知道我正在尝试的事情是否可能吗?如果可以,如何使它正常工作?
迅捷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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.