1.有这个一个需求。。。
2.自定义Uilabel
3.直接上代码
#import <UIKit/UIKit.h>
@interface UnderLineCanChangeColorLabel : UILabel
{
UIColor *lineColor;
}
-(void)setLineColor:(UIColor*)color;
@end
import "UnderLineCanChangeColorLabel.h"
@implementation UnderLineCanChangeColorLabel
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
//-(void)awakeFromNib{
NSString *title = [self titleForState:UIControlStateNormal];
[self setTitle:title forState:UIControlStateNormal];
// [self setText:@"xxx"];
//}
-(void)setLineColor:(UIColor *)color{
lineColor = [color copy];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGRect textRect = self.frame;//label的frame
CGContextRef contextRef = UIGraphicsGetCurrentContext();
if ([lineColor isKindOfClass:[UIColor class]]) {
//CGContextSetStrokeColorWithColor(contextRef, self.textColor.CGColor); // 设置和文字颜色一样
CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor); // 自定义线的颜色
}
CGContextSetLineWidth(contextRef, 2.0f);//下划线粗细
CGPoint leftPoint = CGPointMake(0,textRect.size.height);
CGPoint rightPoint = CGPointMake(textRect.size.width,textRect.size.height);
CGContextMoveToPoint(contextRef, leftPoint.x, leftPoint.y);
CGContextAddLineToPoint(contextRef, rightPoint.x, rightPoint.y);
CGContextStrokePath(contextRef);
}
@end
使用方式
在用的地方 初始化时候使用
[_UnderLineCanChangeColorLabel setLineColor:[UIColor redColor]];
PS:
多谢一些网友的分享。。。