@property (assign, nonatomic) BOOL strikeThroughEnabled; // 是否画线
@property (strong, nonatomic) UIColor *strikeThroughColor; // 画线颜色
(2)在Label.m中
- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect:rect];
CGSize textSize = [[self text] sizeWithFont:[self font]];
NSLog(@"______textSize = %@ , ______rect = %@",NSStringFromCGSize(textSize),NSStringFromCGRect(rect));
CGFloat strikeWidth = textSize.width;
CGRect lineRect;
if ([self textAlignment] == NSTextAlignmentRight)
{
// 画线居中
lineRect = CGRectMake(rect.size.width - strikeWidth, rect.size.height/2, strikeWidth, 1);
// 画线居下
//lineRect = CGRectMake(rect.size.width - strikeWidth, rect.size.height/2 + textSize.height/2, strikeWidth, 1);
}
else if ([self textAlignment] == NSTextAlignmentCenter)
{
// 画线居中
lineRect = CGRectMake(rect.size.width/2 - strikeWidth/2, rect.size.height/2, strikeWidth, 1);
// 画线居下
//lineRect = CGRectMake(rect.size.width/2 - strikeWidth/2, rect.size.height/2 + textSize.height/2, strikeWidth, 1);
}
else
{
// 画线居中
lineRect = CGRectMake(0, rect.size.height/2, strikeWidth, 1);
// 画线居下
//lineRect = CGRectMake(0, rect.size.height/2 + textSize.height/2, strikeWidth, 1);
}
if (self.strikeThroughEnabled)
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [self strikeThroughColor].CGColor);
CGContextFillRect(context, lineRect);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
Label *label = [[Label alloc] initWithFrame:CGRectMake(100, 300, 200, 30)];
label.text =@"Code4App $";
label.backgroundColor = [UIColor yellowColor];
label.textColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
}