一、需求
固定UILabel的宽度大小在一定范围,内容能够自动伸缩
二、实施
首先加好约束:
约束加好之后,需要设置好Autoshrink属性,包括Line break、BaseLine、以及缩小字体所能够达到的最小字体大小。
如果需要在UILabel中添加padding,可以增加以下代码:
@IBDesignable class PaddingLabel: UILabel { @IBInspectable var topInset: CGFloat = 5.0 @IBInspectable var bottomInset: CGFloat = 5.0 @IBInspectable var leftInset: CGFloat = 7.0 @IBInspectable var rightInset: CGFloat = 7.0 override func drawText(in rect: CGRect) { let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset) super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) } override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize( size.width + leftInset + rightInset, height: size.height + topInset + bottomInset) } }
https://stackoverflow.com/questions/27459746/adding-space-padding-to-a-uilabel