我想设置一个UILabel的左插图/边距,但找不到这样做的方法。标签有一个背景集,所以仅仅改变它的原点是行不通的。这将是理想的插入文本10px左右在左手边。


当前回答

Swift 4版的blyabtroi解决方案

let leadingMargin: CGFloat = 10
let trailingMargin: CGFloat = 10

let style = NSMutableParagraphStyle()
style.alignment = .justified
style.firstLineHeadIndent = leadingMargin
style.headIndent = leadingMargin
style.tailIndent = trailingMargin

label.attributedText = NSAttributedString(string: "Label with margins", 
                                          attributes: [NSAttributedStringKey.paragraphStyle: style])

其他回答

我通过子类化UILabel和重写drawTextInRect来解决这个问题:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

斯威夫特3.1:

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

斯威夫特4.2.1:准备

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    super.drawText(in: rect.inset(by: insets))
}

你可能已经猜到了,这是对tc的改编。的答案。它有两个优点:

没有必要通过发送sizeToFit消息来触发它 它只保留标签框架——如果你的标签有背景,而你不想让它缩小,这很方便

如果你不想使用一个额外的父视图来设置背景,你可以子类化UILabel并重写textRectForBounds: limitedtonumberolines:。我会添加一个textEdgeInsets属性或类似的,然后做

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
  return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,textEdgeInsets) limitedToNumberOfLines:numberOfLines];
}

为了健壮性,你可能还想在setTextEdgeInsets:中调用[self setNeedsDisplay],但我通常不这么做。

如果你在ios6 +中使用自动布局,你可以通过在UILabel的子类中调整intrinsicContentSize来实现。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.textAlignment = NSTextAlignmentRight;
    }
    return self;
}

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

很多答案都缺少对sizeThatFits的重写。有了这个子类,你可以创建标签,设置填充,然后输入label。sizetofit(),瞧。

import UIKit

class UILabelEx : UILabel
{
    var padding : UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

    override func drawTextInRect(rect: CGRect) {

        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
    }

    override func sizeThatFits(size: CGSize) -> CGSize
    {

        var adjSize = super.sizeThatFits(size)
        adjSize.width += padding.left + padding.right
        adjSize.height += padding.top + padding.bottom

        return adjSize
    }
}

为了消除单行标签的垂直填充,我做了:

// I have a category method setFrameHeight; you'll likely need to modify the frame.
[label setFrameHeight:font.pointSize];

或者,不带类别,使用:

CGRect frame = label.frame;
frame.size.height = font.pointSize;
label.frame = frame;