效果显示如下:
只需要子类化Label,重写DrawRect()方法即可:
#import "MyLabel.h"
@implementation MyLabel
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
//重写UILabel的drawRect类
- (void)drawRect:(CGRect)rect{
// 删除线
if (_isDelete) {
UIFont *font = [UIFont systemFontOfSize:self.font.pointSize];
CGSize size = CGSizeMake(320, 2000);
// 取得高度
CGRect labelRect = [self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
// 取得上下文
CGContextRef c = UIGraphicsGetCurrentContext();
// 设置删除线颜色
CGContextSetStrokeColorWithColor(c, [UIColor redColor].CGColor);
// 设置线宽
CGContextSetLineWidth(c, 1);
CGContextBeginPath(c);
CGFloat halfWayUp = rect.size.height/2 + rect.origin.y;
CGContextMoveToPoint(c, rect.origin.x , halfWayUp );//开始点
CGContextAddLineToPoint(c, rect.origin.x + labelRect.size.width, halfWayUp);//结束点
CGContextStrokePath(c);
}
if (_isRMB){
UIFont *font = [UIFont systemFontOfSize:self.font.pointSize];
UIFont *fuhaofont = [UIFont systemFontOfSize:20];
UIColor *color = [UIColor redColor];
CGSize size = CGSizeMake(320,2000);
CGRect labelRect = [self.text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
NSString *fuhao = @"¥";
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(c, [UIColor redColor].CGColor);
[fuhao drawAtPoint:CGPointMake(rect.size.width - labelRect.size.width - 100, 5) withAttributes:@{NSFontAttributeName:fuhaofont,NSForegroundColorAttributeName:color}];
CGContextStrokePath(c);
}
// label的字体一直显示不出来,请注意一定要调用super
[super drawRect:rect];
}