ios - 使用自动布局或layoutMargins向UILabel添加填充?

标签 ios uikit autolayout

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

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

enter image description here

最佳答案

如果我是你,我会继承 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;
    }

关于ios - 使用自动布局或layoutMargins向UILabel添加填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879944/

相关文章:

ios - 为什么我的平移手势只能在第二次输入后识别事件?

ios - 寻找如何在 iOS 或 Cocoa 上使用 UIGraphicsSetPDFContextURLForRect

iOS - 半透明模态视图 Controller

ios - UITableView 决定单个行高

ios - AutoLayout 动态 .xib View 高度

iphone - 如何分配 AVPlayer 播放/暂停按钮 iOS?

ios - Swift 中重命名属性的回退

iphone - iOS 7 键盘颜色闪烁

ios - Xcode 自动布局约束不起作用(使用 Storyboard)

ios - 如何以编程方式在父容器中制作两个相同大小的 UIView