自定义UILabel 实现显示偏移量和内边距

需求来源:

我们项目中使用的字体不是很标准,显示到label上会造成偏上两个像素的效果,解决此问题重写了一个label。

UILabel有两个接口是专门用来重写,以此来自定义自己的label,如下:

 // override points. can adjust rect before calling super.
// label has default content mode of UIViewContentModeRedraw
– textRectForBounds:limitedToNumberOfLines:
– drawTextInRect:

上面这两个方法不是用来调用的,只适合被UILabel子类重写

– textRectForBounds:limitedToNumberOfLines:
用来改变label里面文字展示窗口的大小,你可以自己根据文字的多少,来计算窗口的大小

– drawTextInRect:
在绘图环境实现文字的绘制,这个方法里面里面已经配置好了绘图环境,使用方式如下:
1.直接获得当前绘图上下文,
2.接着更改绘图环境设置
3.调用super方法来绘制即可

  • .h 文件
@interface FLBaseMiddleLabel : UILabel
@property (assign, nonatomic) UIEdgeInsets edgeInsets;
@property (assign, nonatomic) CGFloat offset;
@end
  • .m文件
@implementation FLBaseMiddleLabel

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self defaultSetting];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultSetting];
    }
    return self;
}

-(void)defaultSetting {
    self.offset = 0;
    self.edgeInsets = UIEdgeInsetsZero;
}

// 修改绘制文字的区域,edgeInsets增加bounds
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets) limitedToNumberOfLines:numberOfLines];
    rect.origin.x -= self.edgeInsets.left;
    rect.origin.y -= self.edgeInsets.top;
    rect.size.width += self.edgeInsets.left + self.edgeInsets.right;
    rect.size.height += self.edgeInsets.top + self.edgeInsets.bottom;
    return rect;
}

//绘制文字
- (void)drawTextInRect:(CGRect)rect {
    CGRect newRect = rect;
    newRect.origin.y += self.offset;
    if (self.text && ![self.text isEqualToString:@""]) {
        [super drawTextInRect:UIEdgeInsetsInsetRect(newRect, self.edgeInsets)];
        self.hidden = NO;
    } else {
        [super drawTextInRect:UIEdgeInsetsInsetRect(newRect, UIEdgeInsetsZero)];
        self.hidden = YES;
    }
}

你可能感兴趣的:(自定义UILabel 实现显示偏移量和内边距)