使用故事板在 UILabel 中的文本前后添加 space

Adding a space before and after the text in UILabel using the storyboard

如何使用故事板在 UILabel 中的文本前后添加 space。

这是带有背景的标签示例。

一种方法是:

  • 在故事板中使用自动布局。

  • 使用 UILabel subclass 覆盖 intrinsicContentSize 使其比默认值宽一点。

例如:

extension CGSize {
    func sizeByDelta(dw dw:CGFloat, dh:CGFloat) -> CGSize {
        return CGSizeMake(self.width + dw, self.height + dh)
    }
}

class MyWiderLabel : UILabel {
    override func intrinsicContentSize() -> CGSize {
        return super.intrinsicContentSize().sizeByDelta(dw: 20, dh: 0)    
    }
}

现在只需将故事板中每个标签的 class 设置为 MyWiderLabel。