拉伸和字距调整类型,不适用于带有 @IBDesignable 的 Storyboard
Posted
技术标签:
【中文标题】拉伸和字距调整类型,不适用于带有 @IBDesignable 的 Storyboard【英文标题】:Stretching and kerning type, not working in Storyboard with @IBDesignable 【发布时间】:2016-05-17 02:23:02 【问题描述】:这是一个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
右边的模拟器完美运行。
实际上并未在情节提要上实时显示(见左侧)。
猜猜看,我是不是缺少了一个初始化函数?
或者可能是什么问题?
注意 - 设置字体大小以适应高度:
您可能希望设置字体大小以填充所有设备上的标签框。为了节省您的输入,这里有一个执行“point for height”、跟踪和拉伸的类:https://***.com/a/37277874/294884
【问题讨论】:
【参考方案1】:您还应该将代码放入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
【讨论】:
以上是关于拉伸和字距调整类型,不适用于带有 @IBDesignable 的 Storyboard的主要内容,如果未能解决你的问题,请参考以下文章