ios - 是否可以使用@IBDesignable 在 Storyboard中显示 UILabel.attributedText?

标签 ios swift xcode storyboard

我的应用程序中的所有标签都使用设置了间距/字距调整值以及颜色和其他一些东西的字体,我想看看应用了所有这些属性后 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 上呈现

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
    }
}

关于ios - 是否可以使用@IBDesignable 在 Storyboard中显示 UILabel.attributedText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902356/

相关文章:

ios - NSManagedObject(context :) constructor and NSEntityDescription. insertNewObject 用于将新对象插入到 CoreData 中的区别

ios - iOS 中的 CoreGraphics : how can I save the paths drawn in a CGContext and retrieve them in the next draw call?

ios - 使 TableView 部分标题中的按钮 float /以编程方式右对齐//Swift

objective-c - 我可以以编程方式打开和关闭 WiFi 并更改网络吗? (Mac SDK)

objective-c - 为什么我的 NSApplicationDelegate 类中的 applicationWillFinishLaunching 从未被调用?

ios - 使用 J2ObjC 和 GSON 库将 Swift 类序列化为 JSON

ios - 将字符串传递给第二个 View Controller

ios - 在iOS调整 View 中,当且仅当文本字段隐藏在键盘后面时才应该移动,否则不需要调整。

c++ - box2d 迭代

iphone - 使用 CATransition 重新创建 iOS 应用打开过渡