【问题标题】:Add padding to UILabel using Auto Layout or layoutMargins? [duplicate]使用自动布局或 layoutMargins 向 UILabel 添加填充? [复制]
【发布时间】:2015-01-08 21:22:02
【问题描述】:

我想在标签的框架和文本之间添加插图。我认为使用layoutMargins (http://carpeaqua.com/2014/07/24/auto-layout-in-ios-8-layout-margins/) 是可能的,但我无法做到这一点。

我有一个示例项目,您可以在其中看到我在做什么(错了?):https://github.com/runmad/MessagingApp

【问题讨论】:

  • 您误解了布局边距的作用。正如文档所说,“使用此属性指定视图边缘和任何子视图之间所需的空间量(以点为单位)”。所以边距在视图和它的子视图之间,而不是在标签中插入文本 - 文本不是子视图。

标签: ios uikit autolayout


【解决方案1】:

如果我是你,我会继承 UILabel 并添加 UIEdgeInsets。在UILabel 的子类中执行以下操作:

.m 文件

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];

        if (self){

             //Property in the header file so we can add custom insets per instance of this class 
                self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }

        return self;
    }



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

/* So that it will also work with auto layout */ 
    -(CGSize)intrinsicContentSize
    {
        CGSize size = [super intrinsicContentSize];
        size.width += self.edgeInsets.left + self.edgeInsets.right;
        size.height += self.edgeInsets.top + self.edgeInsets.bottom;

        if (self.numberOfLines == 0){

             //There is a bug where intrinsice content
             //size may be 1 point too short

              size.height += 1;
           }

        return size;
    }

【讨论】:

  • 我对此进行了测试,但它并不适用于所有多行标签。特别是当你有一个长词因为插入而被移到下一行时,文本可能会被截断,因为行数没有得到正确计算。
  • 啊,是的,我注意到多行有一个小错误。有一个“错误”有时会导致它太短 1 点。我在多行时遇到了这个问题。我已经用intrinsicContentSize 方法中的if 语句更新了我的答案。试试看。还将您的标签设置为自动换行而不是自动换行。
  • 我试过了,但它仍然不适用于 OP 的示例——长文本仍然被截断(即使高度为 +=20)。我用来关闭问题的链接中接受的答案非常有效。
  • 谢谢@rdelmar - 我在 SO 上搜索了一堆,但没有找到那个帖子/答案。完美运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2023-03-24
相关资源
最近更新 更多