How can I add padding to the intrinsic content size of UILabel?

前端 未结 4 555
南笙
南笙 2021-02-04 02:09

I\'m using autolayout on iOS7 and I have a problem like this:

I\'m putting a UILabel onto a UIView and I\'m arranging my autolayout constraints so that the label\'s cen

4条回答
  •  心在旅途
    2021-02-04 02:20

    You can extend UILabel and override the intrinsicContentSize by yourself. Please make sure you have set the textAlignment = NSTextAlignmentCenter as well.

    -(CGSize)intrinsicContentSize{
        CGSize contentSize = [super intrinsicContentSize];
        return CGSizeMake(contentSize.width + 50, contentSize.height);
    }
    

    Swift 5.0

    open override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + 16, height: size.height)
    }
    

    This probably only works when you only have just one line of text to display.

提交回复
热议问题