添加填充到以编程方式创建的UILabel

问题描述 投票:0回答:2

如何在以编程方式创建的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
2个回答
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

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


1
投票

NSLayoutConstraint是Objc对象。您也可以通过编程方式创建它们。或者您也可以在故事板中创建它们并将插座拖到控制器上并在代码上操作它们。

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

© www.soinside.com 2019 - 2024. All rights reserved.