拉伸和字距调整类型,不适用于 @IBDesignable 的 Storyboard

Stretching and kerning type, not working in Storyboard with @IBDesignable

这里有一个 IBLabel 跟踪/拉伸字体。

它在构建中完美运行。但是这个变化并没有在 Storyboard 中实时显示。

// UILabel, but you can set
// the tracking (that's the overall amount of space between all letters)
// and streching (actually squeeze or stretch the letters horizontally)
// Note: it's very common that typographers need you to adjust these.

import UIKit

@IBDesignable
class StyledLabel: UILabel
    {
    @IBInspectable var tracking:CGFloat = 0.8
    // values between about 0.7 to 1.3.  one means normal.

    @IBInspectable var stretching:CGFloat = -0.1
    // values between about -.5 to .5.  zero means normal.

    override func awakeFromNib()
        {
        let ats = NSMutableAttributedString(string: self.text!)
        let rg = NSRange(location: 0, length: self.text!.characters.count)

        ats.addAttribute(
            NSKernAttributeName, value:CGFloat(tracking), range:rg )

        ats.addAttribute(
            NSExpansionAttributeName, value:CGFloat(stretching), range:rg )

        self.attributedText = ats
        }
    }

右边的模拟器运行完美。

实际上并没有在 Storyboard 上直播(见左图)。

大胆猜测,我是否缺少初始化函数?

或者可能是什么问题?


注意 - 将字体大小设置为适合高度:

您可能需要设置字体大小以填充所有设备上的标签框。为了节省您的输入,这里有一个 class 可以执行 "point for height"、跟踪和拉伸:

您还应该将代码放入 prepareForInterfaceBuilder()。它仅在界面构建器中调用,而不是在运行时调用。

override func prepareForInterfaceBuilder() {
    let ats = NSMutableAttributedString(string: self.text!)
    let rg = NSRange(location: 0, length: self.text!.characters.count)

    ats.addAttribute(
        NSKernAttributeName, value:CGFloat(tracking), range:rg )

    ats.addAttribute(
        NSExpansionAttributeName, value:CGFloat(stretching), range:rg )

    self.attributedText = ats
}