#import <UIKit/UIKit.h>
@interface KeyImageLabel : UILabel
@property(nonatomic, assign) UIEdgeInsets edgeInsets;
@end
#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];
网友评论