我有一个UILabel,我想在上面和下面加空格.使用约束中的最小高度,我已将其修改为:

Enter image description here

为此,我使用了:

override func drawTextInRect(rect: CGRect) {
    var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}

但我必须找到不同的方法,因为如果我写两行以上,问题是一样的:

Enter image description here

推荐答案

如果您想坚持使用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

Ios相关问答推荐

如何以最可靠的方式删除文本视图中的额外页边距?

SwiftUI.从自定义视图修改器访问自定义视图子视图

在SWIFT中将圆角+透明背景从导入视频(.mp4)添加到导出视频(.mov)

DriverKit驱动程序中可能存在IOBufferMemoyDescriptor泄漏

如果条件不满足,S从@ViewBuilder返回什么?

当重新呈现UI时,嵌套的 struct 值如何与@Observable一起工作?

SwiftData在获取值时应用程序崩溃:线程1:EXC_BREAKPOINT(代码=1,子代码=0x101e8303c)

如何在SwiftUI中为带有CornerRadius的矩形创建下边框?

SwiftUI - 搜索栏和导航标题之间的空间太大

Toast 不显示 Flutter

UIView 阴影不适用于自定义扩展

在 Swift 中 @MainActor 似乎被 withCheckedContinuation 而不是其他异步调用继承是巧合吗?

iOS SwiftUI - 从以前的 struct 调用函数

帧过渡动画有条件地工作

使用实时数据库的应用程序无法在被 Firebase 阻止的罗马尼亚 ISP 中运行

在 Swift 中为 UITextField/UIView 摇动动画

如何 comments .plist 文件中的行?

如何在 Swift 中将新单元格插入 UITableView

iOS7 UITextView contentsize.height 替代

UICollectionView flowLayout 没有正确包装单元格