1. New HZSUnderLineLabel.h class integrated from Uilabel
2..h file
//
HZSUnderLineLabel.h
Inface
//
Created by Huangzengsong on 15/5/11.
Copyright (c) 2015 Huangzs. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum{
linetypenone,//No draw line
Linetypeup,//Top draw Line
linetypemiddle,//Middle Draw Line
linetypedown,//Bottom Line
} Linetype;
@interface Hzsunderlinelabel:uilabel
@property (Assign, nonatomic) Linetype Linetype;
@property (Strong, Nonatomic) Uicolor * LINECOLOR;
@end
3..M file
//
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 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) {//Down draw line
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 perform custom drawing.
An empty implementation adversely affects performance during animation.
-(void) DrawRect: (cgrect) Rect {
Drawing Code
}
*/
@end
4. When to adjust
Self. Titlelabel.linetype=linetypedown;
Self. Titlelabel.linecolor=[uicolor Blackcolor];
Label Underline underlined