1. 新建HZSUnderLineLabel.h类集成自UILabel
2..h文件
//
// HZSUnderLineLabel.h
// inface
//
// Created by huangzengsong on 15/5/11.
// Copyright (c) 2015年 huangzs. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum{
LineTypeNone,//没有画线
LineTypeUp ,// 上边画线
LineTypeMiddle,//中间画线
LineTypeDown,//下边画线
} LineType ;
@interface HZSUnderLineLabel : UILabel
@property (assign, nonatomic) LineType lineType;
@property (strong, nonatomic) UIColor * lineColor;
@end
3..m文件
//
// HZSUnderLineLabel.m
// inface
//
// Created by huangzengsong on 15/5/11.
// Copyright (c) 2015年 huangzs. All rights reserved.
//
#import "HZSUnderLineLabel.h"
@implementation HZSUnderLineLabel
- (void)dealloc{
self.lineColor = nil;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.lineColor=[UIColor grayColor];
self.lineType = LineTypeDown;
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (void)drawTextInRect:(CGRect)rect{
[super drawTextInRect:rect];
CGSize textSize = [[self text] sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[self font],NSFontAttributeName, nil]];
CGFloat strikeWidth = textSize.width;
CGRect lineRect;
CGFloat origin_x;
CGFloat origin_y = 0.0;
if ([self textAlignment] == NSTextAlignmentRight) {
origin_x = rect.size.width - strikeWidth;
} else if ([self textAlignment] == NSTextAlignmentCenter) {
origin_x = (rect.size.width - strikeWidth)/2 ;
} else {
origin_x = 0;
}
if (self.lineType == LineTypeUp) {
origin_y = 2;
}
if (self.lineType == LineTypeMiddle) {
origin_y = rect.size.height/2;
}
if (self.lineType == LineTypeDown) {//下画线
origin_y = rect.size.height - 2;
}
lineRect = CGRectMake(origin_x , origin_y, strikeWidth, 1);
if (self.lineType != LineTypeNone) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat R, G, B, A;
NSLog(@"self.lineColor%@",self.lineColor);
CGColorRef color = self.lineColor.CGColor;
NSUInteger numComponents = CGColorGetNumberOfComponents(color);
if( numComponents == 4)
{
const CGFloat *components = CGColorGetComponents(color);
R = components[0];
G = components[1];
B = components[2];
A = components[3];
CGContextSetRGBFillColor(context, R, G, B, 1.0);
}
CGContextFillRect(context, lineRect);
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
4.调用时
self.TitleLabel.lineType=LineTypeDown;
self.TitleLabel.lineColor=[UIColor blackColor];