2

这是一个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
        }
    }

右侧的模拟器完美运行。

在此处输入图像描述

实际上并未在情节提要上实时显示(见左图)。

疯狂的猜测,我是否缺少初始化函数?

或者问题可能是什么?


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

您可能需要设置字体大小以填充所有设备上的标签框。为了节省您的打字时间,这里有一个“指向高度”、跟踪和拉伸的类:https ://stackoverflow.com/a/372​​77874/294884

4

1 回答 1

4

您还应该将代码放入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
}
于 2016-05-18T12:48:27.960 回答