这是跟踪/拉伸字体的IBLabel
。
它在构建中完美运行。但这些变化并没有在故事板中显示。
// 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/37277874/294884
答案 0 :(得分: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
}