Adding a space before and after the text in UILabe

2019-09-08 14:55发布

问题:

How to add a space before and after the text in UILabel using storyboard.

Here is an example of label with a background.

回答1:

One approach is:

  • Use auto layout in the storyboard.

  • Use a UILabel subclass that overrides intrinsicContentSize to be a little wider than the default.

For example:

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)    
    }
}

Now just set the class of every label in your storyboard to be a MyWiderLabel.