ios - 向 UILabel 添加空间/填充

标签 ios uilabel padding

我有一个UILabel,我想在顶部和底部添加空间。根据约束的最小高度,我将其修改为:

Enter image description here

为此,我使用了:

override func drawTextInRect(rect: CGRect) {
    var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}

但我必须找到不同的方法,因为如果我写两行以上,问题是一样的:

Enter image description here

最佳答案

我已经在 Swift 4.2 上尝试过它,希望它对你有用!

@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(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)
    }   

    override var bounds: CGRect {
        didSet {
            // ensures this works within stack views if multi-line
            preferredMaxLayoutWidth = bounds.width - (leftInset + rightInset)
        }
    } 
}

或者您可以在此处使用 CocoaPods https://github.com/levantAJ/PaddingLabel

pod'PaddingLabel','1.2'

enter image description here

关于ios - 向 UILabel 添加空间/填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55825229/

相关文章:

ios - Firebase,离开我的调试器控制台

ios - 在水平 UIStackView 中嵌入三个 UILabels 在 TableView 中给出不同的结果

ios - UILabel TapGesture 未触发

css - 带有固定内部占位符的文本区域

ios - Facebook 登录问题 iOS9 + Parse

ios - iPhone 导航栏标题文本颜色在 iOS 11 中的 viewWillAppear() 或 viewWillDisappear 函数中不会改变

iphone - 如何在 iPhone 中的标签值中添加或连接百分号

html - 将 html 页面中的所有内容向下移动而不更改视频的位置

margin - 如何在 Bootstrap 3 网格系统中调整装订线?

ios - 视频播放GPUImage和swift