美文网首页
自定义Label,设置内边距

自定义Label,设置内边距

作者: c5550ea746f8 | 来源:发表于2017-12-08 22:19 被阅读8次

//#import@interface EdgeInsetsLabel : UILabel

@property(nonatomic, assign) UIEdgeInsets edgeInsets;

@end

复制代码

复制代码

//

//  EdgeInsetsLabel.m

//  EdgeInsetsLabel

//

//  Created by YouXianMing on 14/10/27.

//  Copyright (c) 2014年 YouXianMing. All rights reserved.

//

#import "EdgeInsetsLabel.h"

@implementation EdgeInsetsLabel

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {

UIEdgeInsets insets = self.edgeInsets;

CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)

limitedToNumberOfLines:numberOfLines];

rect.origin.x    -= insets.left;

rect.origin.y    -= insets.top;

rect.size.width  += (insets.left + insets.right);

rect.size.height += (insets.top + insets.bottom);

return rect;

}

- (void)drawTextInRect:(CGRect)rect {

[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];

}

@end

复制代码

ViewController.m

复制代码

//

//  ViewController.m

//  SetInsets

//

//  Created by YouXianMing on 14/10/27.

//  Copyright (c) 2014年 YouXianMing. All rights reserved.

//

#import "ViewController.h"

#import "EdgeInsetsLabel.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

EdgeInsetsLabel *label    = [[EdgeInsetsLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

label.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:30.f];

label.text                = @"No Zuo No Die";

label.edgeInsets          = UIEdgeInsetsMake(8, 8 , 8, 8); //核心一: 设置内边距

[label sizeToFit]; //核心二: 重新计算尺寸,会调用- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines方法

label.layer.cornerRadius  = label.frame.size.height / 2.f;

label.backgroundColor    = [UIColor blackColor];

label.textColor          = [UIColor redColor];

label.layer.masksToBounds = YES;

label.center              = self.view.center;

[self.view addSubview:label];

}

@end

相关文章

网友评论

      本文标题:自定义Label,设置内边距

      本文链接:https://www.haomeiwen.com/subject/lavyixtx.html