如果您想继续使用UILabel,而不必创建其子类,请参考
Mundi所提供的清晰解决方案。
或者,如果您愿意避免将UILabel包装在UIView中,则可以使用UITextView来启用UIEdgeInsets(填充),或者创建UILabel的子类以支持UIEdgeInsets。
只需使用UITextView即可提供插图(Objective-C):
textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
如果您要创建子类UILabel,可以通过覆盖 drawTextInRect 方法来实现此方法的示例
(Objective-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}
你还可以为你的子类化UILabel提供上、左、下和右的内边距变量。
示例代码如下:
在 .h 文件中(Objective-C)
float topInset, leftInset,bottomInset, rightInset;
在.m文件中(Objective-C)
- (void)drawTextInRect:(CGRect)uiLabelRect {
[super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}
根据我看到的,当你对UILabel进行子类化时,似乎必须覆盖intrinscContentSize。
因此,你应该这样覆盖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的大小以匹配边缘插图,并覆盖您提到的多行必要性。
在搜索一番后,我找到了这个Gist,其中包含一个IPInsetLabel。如果这些解决方案都不起作用,您可以尝试使用它。
关于此问题有类似的问题(重复)。
有关可用解决方案的完整列表,请参见此答案:UILabel文本边距