UILabel Text 加下划线

.h文件
#import <Foundation/Foundation.h>

@interface CustomLabel : UILabel
{
    BOOL _isEnabled;
}

@property (nonatomic ) BOOL isEnabled;

@end

.m文件
#import "CustomLabel.h"

@implementation CustomLabel

@synthesize isEnabled = _isEnabled;

- (void)drawTextInRect:(CGRect)rect{
    [super drawTextInRect:rect];
    
    CGSize textSize = [[self text] sizeWithFont:[self font]];
    CGFloat strikeWidth = textSize.width;
    CGRect lineRect;
    
    if ([self textAlignment] == NSTextAlignmentRight) {
        lineRect = CGRectMake(rect.size.width - strikeWidth, rect.size.height/2, strikeWidth, 1);
    } else if ([self textAlignment] == NSTextAlignmentCenter) {
        lineRect = CGRectMake(rect.size.width/2 - strikeWidth/2, rect.size.height/2, strikeWidth, 1);
    } else {
        lineRect = CGRectMake(0, rect.size.height/2, strikeWidth, 1);
    }
    
    if (_isEnabled) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextFillRect(context, lineRect);
    }
}

// 调用

CustomLabel *_label;
 _label = [[CustomLabel alloc]initWithFrame:CGRectMake(50, 100, 0, 40)];
 _label.text = @"这是一个多么美好的世界啊";
 _label.backgroundColor = [UIColor clearColor];
 _label.isEnabled = YES;
 [_label sizeToFit];
  _label.textColor = [UIColor redColor];
 [self.view addSubview:_label];

 

posted @ 2013-07-19 10:24  菜鸟程序猿  阅读(623)  评论(0编辑  收藏  举报