【问题标题】:Add padding to programmatically created UILabel向以编程方式创建的 UILabel 添加填充
【发布时间】:2014-04-02 07:43:21
【问题描述】:

如何向以编程方式创建的UIlabel 文本添加填充?

NSArray *collectionViewArrayTitle = _titleArray[collectionView.index];
 NSString *title=   collectionViewArrayTitle[indexPath.item];
 newslabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 80, 130, 50)];
_newslabel.textColor=[UIColor whiteColor];
_newslabel.backgroundColor=[UIColor blackColor]  ;
_newslabel.alpha=1.0f;
_newslabel.text=title;
_newslabel.tag=collectionView.index;
_newslabel.lineBreakMode=NSLineBreakByTruncatingTail;
_newslabel.numberOfLines=4;

【问题讨论】:

    标签: iphone ios7 uilabel


    【解决方案1】:

    向标签添加“填充”的最佳方法是创建 UILabel 的子类并添加 edgeInsets 属性。

    CustomLabel.h
    
    #import <UIKit/UIKit.h>
    
    @interface CustomLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    CustomLabel.m
    
    #import "CustomLabel.h"
    
    @implementation CustomLabel
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            self.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); //customize padding here
        }
        return self;
    }
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    
    @end
    

    另一种添加填充的方法是使用第二层。这可能更容易完成,但 imo 不是处理它的最干净的方法。您可以添加具有标签大小的 UIView,然后使用一些填充调整该框架。然后,您可以将预期的 UILabel 添加到此视图并使用原点来获得正确的填充。

    【讨论】:

      【解决方案2】:

      NSLayoutConstrains 是 Obj-C 对象。您也可以通过编程方式创建它们。或者您也可以在 Storyboard 中创建它们,然后将插座拖到您的控制器上并在代码上操作它们。

      在代码上,您可以使用 NSConstrain 类来处理,也可以使用 VFL(视觉格式语言)。无论如何,请检查Apple's documentation。一旦你掌握了它,它就很简单了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多