UILabel文字边距

时间:2010-08-13 12:12:18

标签: ios cocoa-touch uikit uilabel

我正在设置UILabel的左侧插入/边距,但找不到这样做的方法。标签有一个背景设置,所以只是改变它的起源不会有效。最好在左侧10px左右插入文本。

38 个答案:

答案 0 :(得分:428)

我通过继承UILabel并覆盖drawTextInRect:来解决这个问题:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
在Swift 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))
}

正如您可能已经收集的那样,这是对tc.'s answer的改编。它比那个有两个优点:

  1. 无需通过发送sizeToFit消息
  2. 来触发它
  3. 它会单独留下标签框 - 如果您的标签有背景并且您不希望它缩小,则很方便

答案 1 :(得分:136)

对于多行文本,可以使用NSAttributedString设置左边距和右边距。

NSMutableParagraphStyle *style =  [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentJustified;
style.firstLineHeadIndent = 10.0f;
style.headIndent = 10.0f;
style.tailIndent = -10.0f;   

NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:title attributes:@{ NSParagraphStyleAttributeName : style}];  

UILabel * label = [[UILabel alloc] initWithFrame:someFrame];
label.numberOfLines = 0;
label.attributedText = attrText;

答案 2 :(得分:86)

向UILabel添加填充的最佳方法是继承UILabel并添加edgeInsets属性。然后,您可以设置所需的插图,并相应地绘制标签。

<强> OSLabel.h

#import <UIKit/UIKit.h>

@interface OSLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

<强> OSLabel.m

#import "OSLabel.h"

@implementation OSLabel

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

- (CGSize)intrinsicContentSize
{
    CGSize size = [super intrinsicContentSize];
    size.width  += self.edgeInsets.left + self.edgeInsets.right;
    size.height += self.edgeInsets.top + self.edgeInsets.bottom;
    return size;
}

@end

答案 3 :(得分:68)

对于这样一个简单的案例,子类化有点麻烦。另一种方法是简单地将没有背景设置的UILabel添加到具有背景设置的UIView。将标签的x设置为10,使外部视图的大小比标签宽20个像素。

答案 4 :(得分:45)

我最后只是在文本中添加了一些空格:

self.titleLabel.text = [NSString stringWithFormat:@"    %@", self.titleLabel.text];

丑陋但有效,不需要子类化。

您也可以尝试“\ t”。有关通用解决方案,请参阅接受的答案

答案 5 :(得分:43)

使用Swift 3,您可以通过创建UILabel的子类来获得所需的效果。在此子类中,您必须添加具有所需insets的UIEdgeInsets属性并覆盖drawText(in:)方法,intrinsicContentSize属性(对于Auto布局代码)和/或sizeThatFits(_:)方法(对于Springs&amp; Struts代码)。

import UIKit

class PaddingLabel: UILabel {

    let padding: UIEdgeInsets

    // Create a new PaddingLabel instance programamtically with the desired insets
    required init(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) {
        self.padding = padding
        super.init(frame: CGRect.zero)
    }

    // Create a new PaddingLabel instance programamtically with default insets
    override init(frame: CGRect) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(frame: frame)
    }

    // Create a new PaddingLabel instance from Storyboard with default insets
    required init?(coder aDecoder: NSCoder) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(coder: aDecoder)
    }

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

    // Override `intrinsicContentSize` property for Auto layout code
    override var intrinsicContentSize: CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let heigth = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

    // Override `sizeThatFits(_:)` method for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

}

以下示例说明如何在PaddingLabel中使用UIViewController个实例:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var storyboardAutoLayoutLabel: PaddingLabel!
    let autoLayoutLabel = PaddingLabel(padding: UIEdgeInsets(top: 20, left: 40, bottom: 20, right: 40))
    let springsAndStructsLabel = PaddingLabel(frame: CGRect.zero)
    var textToDisplay = "Lorem ipsum dolor sit er elit lamet."

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set autoLayoutLabel
        autoLayoutLabel.text = textToDisplay
        autoLayoutLabel.backgroundColor = .red
        autoLayoutLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(autoLayoutLabel)
        autoLayoutLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
        autoLayoutLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        // Set springsAndStructsLabel
        springsAndStructsLabel.text = textToDisplay
        springsAndStructsLabel.backgroundColor = .green
        view.addSubview(springsAndStructsLabel)
        springsAndStructsLabel.frame.origin = CGPoint(x: 30, y: 90)
        springsAndStructsLabel.sizeToFit()

        // Set storyboardAutoLayoutLabel
        storyboardAutoLayoutLabel.text = textToDisplay
        storyboardAutoLayoutLabel.backgroundColor = .blue
    }

    // Link this IBAction to a UIButton or a UIBarButtonItem in Storyboard
    @IBAction func updateLabelText(_ sender: Any) {
        textToDisplay = textToDisplay == "Lorem ipsum dolor sit er elit lamet." ? "Lorem ipsum." : "Lorem ipsum dolor sit er elit lamet."

        // autoLayoutLabel
        autoLayoutLabel.text = textToDisplay

        // springsAndStructsLabel
        springsAndStructsLabel.text = textToDisplay
        springsAndStructsLabel.sizeToFit()

        // storyboardAutoLayoutLabel
        storyboardAutoLayoutLabel.text = textToDisplay
    }

}

答案 6 :(得分:35)

Swift版本的再生钢的回答+ intrinsizeContentSize()

它支持更传统的设置插件的插图,其中包含插件的其他视图对象,同时能够在Interface Builder中设置插件,即插件设置如此编程:

label.inset = UIEdgeInsetsMake(0, 0, 5, 0)

如果有任何错误,请告诉我。

Swift 3

@IBDesignable class InsetLabel: UILabel {
    @IBInspectable var topInset: CGFloat = 0.0
    @IBInspectable var leftInset: CGFloat = 0.0
    @IBInspectable var bottomInset: CGFloat = 0.0
    @IBInspectable var rightInset: CGFloat = 0.0

    var insets: UIEdgeInsets {
        get {
            return UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset)
        }
        set {
            topInset = newValue.top
            leftInset = newValue.left
            bottomInset = newValue.bottom
            rightInset = newValue.right
        }
    }

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

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var adjSize = super.sizeThatFits(size)
        adjSize.width += leftInset + rightInset
        adjSize.height += topInset + bottomInset

        return adjSize
    }

    override var intrinsicContentSize: CGSize {
        var contentSize = super.intrinsicContentSize
        contentSize.width += leftInset + rightInset
        contentSize.height += topInset + bottomInset

        return contentSize
    }
}

Swift 2.2

@IBDesignable class InsetLabel: UILabel {
    @IBInspectable var topInset: CGFloat = 0.0
    @IBInspectable var leftInset: CGFloat = 0.0
    @IBInspectable var bottomInset: CGFloat = 0.0
    @IBInspectable var rightInset: CGFloat = 0.0

    var insets: UIEdgeInsets {
        get {
            return UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset)
        }
        set {
            topInset = newValue.top
            leftInset = newValue.left
            bottomInset = newValue.bottom
            rightInset = newValue.right
        }
    }

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

    override func sizeThatFits(size: CGSize) -> CGSize {
        var adjSize = super.sizeThatFits(size)
        adjSize.width += leftInset + rightInset
        adjSize.height += topInset + bottomInset

        return adjSize
    }

    override func intrinsicContentSize() -> CGSize {
        var contentSize = super.intrinsicContentSize()
        contentSize.width += leftInset + rightInset
        contentSize.height += topInset + bottomInset

        return contentSize
    }
}

答案 7 :(得分:29)

您也可以通过使用自定义框架初始化UILabel来解决此问题。

    CGRect initialFrame = CGRectMake(0, 0, 100, 100);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    CGRect paddedFrame = UIEdgeInsetsInsetRect(initialFrame, contentInsets);

    self.label = [[UILabel alloc] initWithFrame:paddedFrame];

CGRect Tricks

答案 8 :(得分:17)

对于Xamarin用户(使用Unified API):

class UIMarginLabel : UILabel
{
    public UIMarginLabel()
    {
    }

    public UIMarginLabel( CGRect frame ) : base( frame )
    {
    }

    public UIEdgeInsets Insets { get; set; }

    public override void DrawText( CGRect rect )
    {
        base.DrawText( Insets.InsetRect( rect ) );
    }
}

对于那些使用原始MonoTouch API的人:

public class UIMarginLabel : UILabel
{
    public UIEdgeInsets Insets { get; set; }

    public UIMarginLabel() : base()
    {
        Insets = new UIEdgeInsets(0, 0, 0, 0);
    }
    public UIMarginLabel(RectangleF frame) : base(frame)
    {
        Insets = new UIEdgeInsets(0, 0, 0, 0);
    }

    public override void DrawText(RectangleF frame)
    {
        base.DrawText(new RectangleF(
            frame.X + Insets.Left,
            frame.Y + Insets.Top,
            frame.Width - Insets.Left - Insets.Right,
            frame.Height - Insets.Top - Insets.Bottom));
    }
}

答案 9 :(得分:13)

和@IBDesignable,使其适用于Interface Builder

Swift 4

//
//  PaddedLabel.swift
//  TrainCentric
//
//  Created by Arsonik
//  https://stackoverflow.com/a/33244365/337934
//

import UIKit

@IBDesignable
class PaddedLabel: UILabel {

    @IBInspectable var inset:CGSize = CGSize(width: 0, height: 0)

    var padding: UIEdgeInsets {
        var hasText:Bool = false
        if let t = self.text?.count, t > 0 {
            hasText = true
        }
        else if let t = attributedText?.length, t > 0 {
            hasText = true
        }

        return hasText ? UIEdgeInsets(top: inset.height, left: inset.width, bottom: inset.height, right: inset.width) : UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: padding))
    }

    override var intrinsicContentSize: CGSize {
        let superContentSize = super.intrinsicContentSize
        let p = padding
        let width = superContentSize.width + p.left + p.right
        let heigth = superContentSize.height + p.top + p.bottom
        return CGSize(width: width, height: heigth)
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let p = padding
        let width = superSizeThatFits.width + p.left + p.right
        let heigth = superSizeThatFits.height + p.top + p.bottom
        return CGSize(width: width, height: heigth)
    }
}

Swift 2

@IBDesignable
class PaddedLabel: UILabel {

    @IBInspectable var inset:CGSize = CGSize(width: 0, height: 0)

    var padding: UIEdgeInsets {
        var hasText:Bool = false
        if let t = text?.length where t > 0 {
            hasText = true
        }
        else if let t = attributedText?.length where t > 0 {
            hasText = true
        }

        return hasText ? UIEdgeInsets(top: inset.height, left: inset.width, bottom: inset.height, right: inset.width) : UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
    }

    override func intrinsicContentSize() -> CGSize {
        let superContentSize = super.intrinsicContentSize()
        let p = padding
        let width = superContentSize.width + p.left + p.right
        let heigth = superContentSize.height + p.top + p.bottom
        return CGSize(width: width, height: heigth)
    }

    override func sizeThatFits(size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let p = padding
        let width = superSizeThatFits.width + p.left + p.right
        let heigth = superSizeThatFits.height + p.top + p.bottom
        return CGSize(width: width, height: heigth)
    }
}

答案 10 :(得分:12)

要扩展Brody Robertson提供的答案,您可以添加IB Designable位。这意味着您可以在Storyboard中调整标签。

enter image description here

在您的子类UILabel中

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface insetLabel : UILabel

@property (nonatomic, assign) IBInspectable CGFloat leftEdge;
@property (nonatomic, assign) IBInspectable CGFloat rightEdge;
@property (nonatomic, assign) IBInspectable CGFloat topEdge;
@property (nonatomic, assign) IBInspectable CGFloat bottomEdge;

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

然后做;

#import "insetLabel.h"

@implementation insetLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.edgeInsets = UIEdgeInsetsMake(self.topEdge, self.leftEdge, self.bottomEdge, self.rightEdge);
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect
{
    self.edgeInsets = UIEdgeInsetsMake(self.topEdge, self.leftEdge, self.bottomEdge, self.rightEdge);

    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

- (CGSize)intrinsicContentSize
{
    CGSize size = [super intrinsicContentSize];
    size.width  += self.edgeInsets.left + self.edgeInsets.right;
    size.height += self.edgeInsets.top + self.edgeInsets.bottom;
    return size;
}

@end

修改

你应该为edgeInsets添加一个setter方法。

答案 11 :(得分:10)

如果您不想使用额外的父视图来设置背景,则可以继承UILabel并覆盖textRectForBounds:limitedToNumberOfLines:。我将添加textEdgeInsets属性或类似属性,然后执行

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

为了健壮,您可能还想在setTextEdgeInsets中调用[self setNeedsDisplay],但我通常不会打扰。

答案 12 :(得分:10)

也许晚些时候为派对,但以下只是有效。只是UILabel的子类。

timestamps                        mins
2013-06-23 00:00:00               NA
2013-06-23 01:00:00               60
2013-06-23 02:00:00               60
2013-06-23 04:00:00              120

答案 13 :(得分:6)

这是一个快速的解决方案。只需在文件底部添加此自定义类(或为其创建新文件),并在创建标签时使用MyLabel而不是UILabel。

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

答案 14 :(得分:6)

如果您在iOS 6+中使用autolayout,则可以通过调整intrinsicContentSize的子类中的UILabel来执行此操作。

- (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);
}

答案 15 :(得分:5)

在Swift中它解决了这个问题。

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

答案 16 :(得分:5)

而不是UILabel可能使用https://github.com/mattt/TTTAttributedLabel

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

答案 17 :(得分:4)

blyabtroi's asnwer转换为Swift(无需子类)

let style: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
style.alignment = .Justified
style.firstLineHeadIndent = 10.0
style.headIndent = 10.0
style.tailIndent = -10.0
let attrText: NSAttributedString = NSAttributedString(string: title, attributes: [NSParagraphStyleAttributeName:style])
let label: UILabel = UILabel(frame: someFrame)
label.numberOfLines = 0
label.attributedText = attrText

答案 18 :(得分:4)

这适用于多行标签:

class PaddedLabel: UILabel {
    var verticalPadding: CGFloat = 0
    var horizontalPadding: CGFloat = 0

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

    override var intrinsicContentSize: CGSize {
        get {
            let textWidth = super.intrinsicContentSize.width - horizontalPadding * 2
            let textHeight = sizeThatFits(CGSize(width: textWidth, height: .greatestFiniteMagnitude)).height
            let width = textWidth + horizontalPadding * 2
            let height = textHeight + verticalPadding * 2
            return CGSize(width: frame.width, height: height)
        }
    }
}

答案 19 :(得分:4)

许多答案都缺少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
    }
}

答案 20 :(得分:3)

这是我为此找到的最简单的解决方案:

快捷键4

class CustomLabel: UILabel{
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)))
    }
}

确保在代码和情节提要中将标签设置为CustomLabel

答案 21 :(得分:3)

Swift 3&amp; AutoLayout 兼容版本:

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
    }
}

答案 22 :(得分:3)

在上述答案中,我没有找到使用UIButton的建议。因此,我将尝试证明这是一个不错的选择。

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

  • 我有一个简单的单行文字
  • 我不想将UIView用作UILabel的容器(即,我想简化单元格中自动布局的数学计算)
  • 我不想使用NSParagraphStyle(因为tailIndent在自动排版中无法正常工作-UILabel的宽度小于预期)
  • 我不想使用UITextView(因为可能会有副作用)
  • 我不想继承UILabel(更少的代码,更少的错误)

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

希望这会对某人有所帮助。

答案 23 :(得分:2)

没有子类化和所有爵士乐......我动态地做了这个:

[cell.textLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[cell.textLabel constraintTrailingEqualTo:cell.contentView constant:-100];

约束部分只是一个简单的代码糖包装器(我们有相同的方法从顶部/底部/左/右添加填充)..如果我在这里得到足够的爱,我将开源整个包装:< / p>

- (id)constraintTrailingEqualTo:(UIView *)toView constant:(CGFloat)constant
{
    NSLayoutConstraint *cn = [NSLayoutConstraint constraintWithItem:self
                                                          attribute:NSLayoutAttributeTrailing
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:toView
                                                          attribute:NSLayoutAttributeTrailing
                                                         multiplier:1 constant:constant];

    [toView addConstraint:cn];
    return self;
}

(注意我在

的背景下这样做了
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath;

根据您的具体情况,您可能需要致电[self setNeedsLayout];

答案 24 :(得分:2)

blyabtroi解决方案的Swift 4版本

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])

答案 25 :(得分:2)

Xcode 6.1.1使用扩展的Swift解决方案。

文件名可以是“UILabel + AddInsetMargin.swift”:

import UIKit

extension UILabel
{
    public override func drawRect(rect: CGRect)
    {
        self.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)))
    }
}

答案 26 :(得分:2)

#import "E_LabelWithPadding.h"
#define padding UIEdgeInsetsMake(2, 0, 2, 0)
#define padding1 UIEdgeInsetsMake(0, 0, 0, 0)
@implementation E_LabelWithPadding
- (void)drawTextInRect:(CGRect)rect {
if (![self.text isEqualToString:@""]) {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding)];
}else {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding1)];
}

}

- (CGSize) intrinsicContentSize {
if (![self.text isEqualToString:@""]) {
    CGSize superContentSize = [super intrinsicContentSize];
    CGFloat width = superContentSize.width + padding.left + padding.right;
    CGFloat height = superContentSize.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}else {
    CGSize superContentSize = [super intrinsicContentSize];
    CGFloat width = superContentSize.width + padding1.left + padding1.right;
    CGFloat height = superContentSize.height + padding1.top + padding1.bottom;
    return CGSizeMake(width, height);
}

}

- (CGSize) sizeThatFits:(CGSize)size {
if (![self.text isEqualToString:@""]) {
    CGSize superSizeThatFits = [super sizeThatFits:size];
    CGFloat width = superSizeThatFits.width + padding.left + padding.right;
    CGFloat height = superSizeThatFits.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}else {
    CGSize superSizeThatFits = [super sizeThatFits:size];
    CGFloat width = superSizeThatFits.width + padding1.left + padding1.right;
    CGFloat height = superSizeThatFits.height + padding1.top + padding1.bottom;
    return CGSizeMake(width, height);
}

}

@end

答案 27 :(得分:0)

放置插图时,您需要计算UILabel大小。由于文本对齐,换行模式,它可以具有不同的行数。

if (remaining == 0) {
  return true;
}
...
if (change(...)) return true;
...
return false;  // It's last line of body

try iEun/InsetLabel

答案 28 :(得分:0)

我已经使用xcode生成器解决了它(但是可以肯定的是,使用约束快速实现):

只需创建一个相关大小的UIView 并将UILabel类型的子项添加到该视图

然后您就可以进行填充了:)

xcode builder solution

答案 29 :(得分:0)

如果标签是通过编程创建的,则可以使用sizeThatFits方法计算填充。如果使用多行,则文本将以最大宽度值换行。

let text = UILabel()
let padding = 10
text.layer.cornerRadius = 5
text.layer.masksToBounds = true
text.text = "Hello"
text.font = UIFont(name: text.font.fontName, size: 18)
text.textAlignment = NSTextAlignment.center
text.numberOfLines = 1

let maxSize = CGSize(width: 100, height: 100)
var size = text.sizeThatFits(maxSize)
size.width = size.width + padding * 2
size.height = size.height + padding * 2
text.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)

答案 30 :(得分:0)

只需向左侧添加空格如果是单行,则多行1行将再次填充0。

[self.myLabel setText:[NSString stringWithFormat:@"   %@", self.myShortString]];

答案 31 :(得分:0)

我认为UILabel类没有设置保证金的方法。为什么不在所需位置设置Label的位置?

见下面的代码:

UILabel *label = [[UILabel alloc] init];
label.text = @"This is label";
label.frame = CGRectMake(0,0,100,100);

如果来自界面构建器,则只需通过以下方式定位Label:

yourLabel.frame = CGRectMake(0,0,100,100);

答案 32 :(得分:0)

也许你可以试试这段代码

CGRect frame = btn.titleLabel.frame;
int indent = 20;
int inset = 20;
[btn.titleLabel setFrame:CGRectMake(frame.origin.x+inset,frame.origin.y,frame.size.width+indent,frame.size.height)];

答案 33 :(得分:0)

为了摆脱单行标签的垂直填充,我做了:

// 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;

答案 34 :(得分:-1)

这是我找到的最简单的方法。它对我来说就像一个魅力。

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];

答案 35 :(得分:-2)

很多这些答案都很复杂。在某些情况下,这是必要的。但是,如果您正在阅读此文章,您的标签没有左/右边距,您只需要一点填充,这是整个解决方案:

步骤1:在末尾添加空格(字面意思是,按空格键几次)

步骤2:将标签的文本对齐方式设置为居中

完成

答案 36 :(得分:-3)

将标签的textAlignment属性设置为NSTextAlignmentRight并增加其宽度。

答案 37 :(得分:-6)

不要编码,Xcode!

我建议您先看看 UIButton ,而不是使用 UILabel 来解决这个问题。它提供了开箱即用的功能,可以在“大小”检查器中设置内容插入(上,左,下,右)。设置所需的边距,然后在Xcode中完成 禁用 按钮并完成。