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


当前回答

Swift 3 &自动布局兼容版本:

class InsetLabel: UILabel {

    var insets = UIEdgeInsets()

    convenience init(insets: UIEdgeInsets) {
        self.init(frame: CGRect.zero)
        self.insets = insets
    }

    convenience init(dx: CGFloat, dy: CGFloat) {
        let insets = UIEdgeInsets(top: dy, left: dx, bottom: dy, right: dx)
        self.init(insets: insets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

    override var intrinsicContentSize: CGSize  {
        var size = super.intrinsicContentSize
        size.width += insets.left + insets.right
        size.height += insets.top + insets.bottom
        return size
    }
}

其他回答

Swift 3 &自动布局兼容版本:

class InsetLabel: UILabel {

    var insets = UIEdgeInsets()

    convenience init(insets: UIEdgeInsets) {
        self.init(frame: CGRect.zero)
        self.insets = insets
    }

    convenience init(dx: CGFloat, dy: CGFloat) {
        let insets = UIEdgeInsets(top: dy, left: dx, bottom: dy, right: dx)
        self.init(insets: insets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

    override var intrinsicContentSize: CGSize  {
        var size = super.intrinsicContentSize
        size.width += insets.left + insets.right
        size.height += insets.top + insets.bottom
        return size
    }
}

这是我发现的最简单的方法。这对我来说很有魔力。

UIView *titleSection = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 100)];
[titleSection addSubview:titleSection];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(titleSection.frame, PADDING, 0)];
[titleSection addSubview:label];

可以使用https://github.com/mattt/TTTAttributedLabel代替UILabel

BITAttributedLabel *label = [BITAttributedLabel new];
label.font = font;
label.text = @"hello";
label.textInsets = UIEdgeInsetsMake(10, 10, 10, 10);
[label sizeToFit];

在Swift中,它是这样解决的。

class Label: UILabel {
    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)))
    }
}

我没有在上面的答案中找到使用UIButton的建议。我会试着证明这是一个好的选择。

按钮。contenttedgeinsets = UIEdgeInsets(上:0,左:8,下:0,右:8)

在我的情况下,使用UIButton是最好的解决方案,因为:

我有一个简单的单行文本 我不想使用UIView作为容器UILabel(即,我想简化数学计算的自动布局在我的单元格) 我不想使用NSParagraphStyle(因为tailIndent与自动布局的工作不正确- UILabel的宽度小于预期) 我不想使用UITextView(因为可能的副作用) 我不想子类化UILabel(少代码少bug)

这就是为什么在我的情况下使用UIButton中的contenttedgeinsets成为添加文本边距的最简单方法。

希望这能帮助到一些人。