简体   繁体   English

添加填充到内在内容大小不适用于UILabel

[英]Add padding to Intrinsic Content Size not working in UILabel

I want to have extra paddings to these UILabels.I changed the intrinsic content size with the following code: 我想为这些UILabels添加额外的填充。我使用以下代码更改了内在内容大小:

class CustomLabelWithPadding:UILabel{


    override func intrinsicContentSize() -> CGSize {
        let contentSize = super.intrinsicContentSize()
        return CGSize(width: contentSize.width + 50, height: contentSize.height)
    }

}

However the label is not having padding as 但是标签没有填充 在此输入图像描述

 let label = CustomLabelWithPadding()
 label.text = "Hello World"
 label.font = UIFont(name: "Helvetica", size: 20)
 label.sizeToFit()
 label.layer.backgroundColor = UIColor(red: 0.067, green: 0.773, blue: 0.525, alpha: 1.00).CGColor
 label.textAlignment = NSTextAlignment.Center
 label.textColor = UIColor.whiteColor()
 label.frame.origin.x = 160
 label.frame.origin.y = 50
 self.view.addSubview(label)

This one did the job :) 这个人完成了工作:)

class CustomLabelWithPadding:UILabel{

    var edgeInsets:UIEdgeInsets = UIEdgeInsetsZero

    override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        var rect = super.textRectForBounds(UIEdgeInsetsInsetRect(bounds, edgeInsets), limitedToNumberOfLines: numberOfLines)

        rect.size.width  += 10;
        return rect
    }

    override func drawTextInRect(rect: CGRect) {
        self.clipsToBounds = true
        self.layer.cornerRadius = 3
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, edgeInsets))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM