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

℡╲_俬逩灬. 提交于 2019-12-03 00:06:24
Vincent

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.

You can create a UILabel subclass and override intrinsicContent,

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

This will add a padding of 20 points to the width. If you want your text in the middle, be sure to set the text alignment to center.

If you're using auto layout, you can set the horizontal constraints and use an NSDictionary in the metrics parameter to set this dynamically.

For instance, if you wanted to give a 10pt padding to the inner content of a UIButton, you could do something like the following:

NSDictionary *padding = @{ @"padding" : @(button.intrinsicContentSize.width + 20) };
NSArray *buttonHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button(==padding)]|" options:0 metrics:padding views:NSDictionaryOfVariableBindings(button)];

If you are trying to give the UILabel a different colour to its parent view, then you will need to enclose the UILabel in a UIView with the padding and the background colour you want. If your UILabels background colour is the same as its parent view, then I don't understand the problem just use auto layout to specify how much space you want relative to the thing it is next to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!