iOS 适配

iOS 10 UILabel 内边距实现方法源码

2017-03-22  本文已影响214人  1b3bd36d9d21
#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];
上一篇下一篇

猜你喜欢

热点阅读