iOS 10 UILabel 内边距实现方法源码
2017-03-22 本文已影响214人
1b3bd36d9d21
- .h头文件
#import <UIKit/UIKit.h>
@interface KeyImageLabel : UILabel
@property(nonatomic, assign) UIEdgeInsets edgeInsets;
@end
- .m源文件
#import "KeyImageLabel.h"
@implementation KeyImageLabel
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.clipsToBounds = YES;
}
return self;
}
// 核心代码
- (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)];
}
/*
- (void)layoutSubviews {
[super layoutSubviews];
self.layer.cornerRadius = self.frame.size.width / 2.0;
}
*/
@end
- 使用方法
KeyImageLabel *label = [[KeyImageLabel alloc] init];
......
label.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
[self.view addSubView:label];