代码之家  ›  专栏  ›  技术社区  ›  Ljdawson

ui标签文本边距

  •  286
  • Ljdawson  · 技术社区  · 15 年前

    我要设置的是 UILabel 找不到这样做的方法。这个标签有一个背景设置,所以仅仅改变它的来源就不会有什么效果。最好将文本插入 10px 在左手边。

    38 回复  |  直到 7 年前
        1
  •  425
  •   Community Mohan Dere    9 年前

    我通过子类化解决了这个问题 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. 它使标签框保持独立-如果标签有背景,而您不想缩小,则使用方便。
        2
  •  135
  •   ivan_pozdeev RenanSS    11 年前

    对于多行文本,可以使用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;
    
        3
  •  79
  •   progrmr    11 年前

    向uilabel添加填充的最佳方法是将uilabel子类化并添加edgeinsets属性。然后设置所需的插入,标签将相应地绘制。

    OsLab.h

    #import <UIKit/UIKit.h>
    
    @interface OSLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    

    OsLab.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
    
        4
  •  67
  •   Peter DeWeese    7 年前

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

        5
  •  43
  •   Yariv Nissim    11 年前

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

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

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

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

        6
  •  42
  •   Imanou Petit    9 年前

    使用Swift 3,您可以通过创建 UILabel . 在这个子类中,您必须添加 UIEdgeInsets 具有必需的插入和重写的属性 drawText(in:) 方法, intrinsicContentSize 属性(用于自动布局代码)和/或 sizeThatFits(_:) 方法(用于弹簧和支柱代码)。

    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
        }
    
    }
    
        7
  •  33
  •   funct7    9 年前

    再生钢的快速版本的答案+ intrinsizeContentSize() .

    它支持为具有插入的其他视图对象设置插入的更传统的样式,同时能够在Interface Builder中设置插入,即插入的设置方式与编程方式类似:

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

    如果有虫子请告诉我。

    斯威夫特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
        }
    }
    

    斯威夫特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
        }
    }
    
        8
  •  28
  •   neverbendeasy    12 年前

    也可以通过用自定义框架初始化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 .

        9
  •  16
  •   Johannes Rudolph    10 年前

    对于Xamarin用户(使用统一API):

    class UIMarginLabel : UILabel
    {
        public UIMarginLabel()
        {
        }
    
        public UIMarginLabel( RectangleF frame ) : base( frame )
        {
        }
    
        public UIEdgeInsets Insets { get; set; }
    
        public override void DrawText( CGRect rect )
        {
            base.DrawText( Insets.InsetRect( rect ) );
        }
    }
    

    对于使用原始单触式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));
        }
    }
    
        10
  •  11
  •   Recycled Steel    10 年前

    要扩展Brody Robertson提供的答案,可以添加ib可指定位。这意味着您可以从故事板内调整标签。

    在子类uilabel中

    import<uikit/uikit.h>
    
    可设计的
    
    @接口插入标签:uiLabel
    
    @属性(nonatomic,assign)IBinspectable CGfloat leftedge;
    @属性(nonatomic,assign)IBinspectable CGfloat rightedge;
    @属性(非原子,赋值)IBinspectable CGFloat TopEdge;
    @属性(非原子,赋值)IBinspectable CGfloat BottomEdge;
    
    @属性(nonatomic,assign)uiedgeinsets edgeinsets;
    
    @结束
    < /代码> 
    
    

    那么,

    import“insetlabel.h”
    
    @实现InsetLabel
    
    -(id)initwithframe:(cgrect)帧
    {
    self=[super initwithframe:frame];
    如果(自己)
    {
    self.edgeinsets=uiedgeinsetmake(self.topedge、self.leftedge、self.bottomedge、self.rightedge);
    }
    回归自我;
    }
    
    -(无效)drawtextinct:(cgrect)rect
    {
    self.edgeinsets=uiedgeinsetmake(self.topedge、self.leftedge、self.bottomedge、self.rightedge);
    
    [超级绘图文本输入:uiedgeinsettrect(rect,self.edgeinsets)];
    }
    
    -(cgsize)内部内容大小
    {
    cgsize size=[超级内部内容大小];
    size.width+=self.edgeinsets.left+self.edgeinsets.right;
    size.height+=self.edgeinsets.top+self.edgeinsets.bottom;
    返回大小;
    }
    
    @结束
    < /代码> 
    
    <>编辑< /P>
    
    

    您可能应该为Edgeinsets添加一个setter方法。

    零位。这意味着您可以从故事板中调整标签。

    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
    

    编辑

    您可能应该为Edgeinset添加一个setter方法。

        11
  •  10
  •   tc.    15 年前

    如果不想使用额外的父视图来设置背景,可以将uilabel子类化并重写 textRectForBounds:limitedToNumberOfLines: . 我会添加textedgeinsets属性或类似属性,然后执行

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

    为了增强健壮性,您可能还想在setextedgeinsets中调用[self-setneedsDisplay],但我通常不费心。

        12
  •  10
  •   valvoline    10 年前

    也许会晚些时候参加聚会,但下面的就行了。只是uilabel的子类。

    #import "UITagLabel.h"
    
    #define padding UIEdgeInsetsMake(5, 10, 5, 10)
    
    @implementation UITagLabel
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding)];
    }
    
    - (CGSize) intrinsicContentSize {
        CGSize superContentSize = [super intrinsicContentSize];
        CGFloat width = superContentSize.width + padding.left + padding.right;
        CGFloat height = superContentSize.height + padding.top + padding.bottom;
        return CGSizeMake(width, height);
    }
    
    - (CGSize) sizeThatFits:(CGSize)size {
        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);
    }
    
    @end
    
        13
  •  10
  •   SamB    7 年前

    以及一个@ibdesignable,使其能够与Interface Builder一起工作

    斯威夫特4

    //
    //  PaddedLabel.swift
    //  TrainCentric
    //
    //  Created by Arsonik
    //  https://stackoverflow.com/a/33244365/337934
    //
    
    import Foundation
    
    @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)
        }
    }
    

    斯威夫特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)
        }
    }
    
        14
  •  6
  •   Ian Terrell    12 年前

    如果您在iOS 6+中使用自动布局,可以通过调整 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
  •  6
  •   rsc user10692571    10 年前

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

    class MyLabel: UILabel{
        override func drawTextInRect(rect: CGRect) {
            super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)))
        }
    }
    
        16
  •  5
  •   Peter DeWeese    11 年前

    而不是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
  •  5
  •   Andrey Gagan    11 年前

    它很快就这样解决了。

    class Label: UILabel {
        override func drawTextInRect(rect: CGRect) {
            super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)))
        }
    }
    
        18
  •  4
  •   Quincy    11 年前

    很多答案都缺少对sizethatfits的覆盖。使用这个子类,您可以创建标签,设置填充,然后说label.sizetofit()和voila。

    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
        }
    }
    
        19
  •  4
  •   Abdul Hannan    9 年前

    blyabtroi的asnewr转换为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
    
        20
  •  4
  •   fhucho    8 年前

    这对多行标签正确工作:

    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)
            }
        }
    }
    
        21
  •  3
  •   mokagio codeWhisperer    8 年前

    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
        }
    }
    
        22
  •  3
  •   sig    7 年前

    我找不到建议使用 UIButton 在上面的答案中。所以我会努力证明这是一个很好的选择。

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

    • 我有一个简单的单行文本
    • 我不想用 UIView 作为容器 UILabel (例如,我想简化计算,以便在我的单元格中自动布局)
    • 我不想用 NSParagraphStyle (因为 tailIndent 工作不正确,自动布局宽度为 乌拉贝尔 小于预期)
    • 我不想用 UITextView (因为可能有副作用)
    • 我不想再分类 乌拉贝尔 (减少代码减少错误)

    这就是为什么使用 contentEdgeInsets 乌布顿 在我的处境下 成为添加文本边距的最简单方法。

    希望这能帮助别人。

        23
  •  2
  •   Andrew MasterUZ    11 年前

    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)))
        }
    }
    
        24
  •  2
  •   abbood    10 年前

    没有子类化和所有的爵士乐。我动态地做到了这一点:

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

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

    - (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]; 取决于你的背景。

        25
  •  2
  •   Hemanshu Liya    9 年前
    #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
    
        26
  •  1
  •   A.Silva    7 年前

    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])
    
        27
  •  0
  •   Adam    13 年前

    我想 UILabel 类没有设置边距的方法。为什么不将标签位置设置在所需位置?

    见下面代码:

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

    如果来自Interface Builder,则只需通过以下方式定位标签:

    yourLabel.frame = CGRectMake(0,0,100,100);
    
        28
  •  0
  •   Chris Prince    11 年前

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

    // 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;
    
        29
  •  0
  •   christian mini    9 年前

    也许你可以试试这个代码

    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)];
    
        30
  •  0
  •   emotality    8 年前

    只需在左侧添加空格 如果是单线的话 ,超过1行将再次有0个填充。

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