如果您想坚持使用UILabel,而不是对其进行子类化,那么Mundi has given you a clear solution.
或者,如果您希望避免使用UIView包装UILabel,则可以使用UITextView来启用UIEdgeInsets(填充)或子类UILabel来支持UIEdgeInsets.
使用UITextView只需提供插图(目标C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(Objective-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
您还可以为新的子类UILabel提供TOP、LEFT、BOOT和RIGHT的插入变量.
示例代码可以是:
In .h (Objective-C)
float topInset, leftInset,bottomInset, rightInset;
In .m (Objective-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
据我所见,似乎在对UILabel进行子类化时,您必须重写UILabel的IntrinsicContentSize.
所以你应该覆盖intrinsicContentSize,比如:
- (CGSize) intrinsicContentSize {
CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
intrinsicSuperViewContentSize.height += topInset + bottomInset ;
intrinsicSuperViewContentSize.width += leftInset + rightInset ;
return intrinsicSuperViewContentSize ;
}
并添加以下方法来编辑插图,而不是单独编辑它们:
- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
topInset = edgeInsets.top;
leftInset = edgeInsets.left;
rightInset = edgeInsets.right;
bottomInset = edgeInsets.bottom;
[self invalidateIntrinsicContentSize] ;
}
它将更新您的UILabel的大小以匹配边缘插入,并覆盖您提到的多行必要性.
在搜索了一下之后,我找到了这个带有IPInsetLabel的Gist.如果这些解决方案都不管用,你可以试试.
There was a similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin