笔记->带中(下)划线的Label

创建个类继承自UILabel

在.h中做如下操作

先在.h文件中设置个枚举:

typedef NS_ENUM(NSInteger, StrikeLineStyle)  {

StrikeLineStyleMiddle,//中间划线

StrikeLineStyleBottom//底部划线

};

并在.h文件中设置3个公开的属性,以便被调用:

@property (nonatomic,assign) StrikeLineStyle  strkeLineStyle;

@property (nonatomic,assign) BOOL  strikeThroughEnabled;// 是否画线

@property (nonatomic,strong) UIColor  *strikeThroughColor;// 画线颜色

在.m文件中做一下操作:

- (void)drawTextInRect:(CGRect)rect {

[superdrawTextInRect:rect];

CGSize textSize = [self.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20,MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size;

CGFloat  strikeWidth = textSize.width;

CGRect  lineRect =CGRectZero;

if([self  textAlignment] ==NSTextAlignmentRight) {

switch(self.strkeLineStyle) {

case  StrikeLineStyleMiddle:

// 画线居中

lineRect =CGRectMake(rect.size.width- strikeWidth, rect.size.height/2, strikeWidth,1);

break;

case  StrikeLineStyleBottom:

// 画线居下

lineRect =CGRectMake(rect.size.width- strikeWidth, rect.size.height/2+ textSize.height/2, strikeWidth,1);

break;

default:

break;

}

}else if([self  textAlignment] ==NSTextAlignmentCenter){

switch(self.strkeLineStyle) {

case  StrikeLineStyleMiddle:

// 画线居中

lineRect =CGRectMake(rect.size.width/2- strikeWidth/2, rect.size.height/2, strikeWidth,1);

break;

case  StrikeLineStyleBottom:

// 画线居下

lineRect =CGRectMake(rect.size.width/2- strikeWidth/2, rect.size.height/2+ textSize.height/2, strikeWidth,1);

break;

default:

break;

}

}else{

switch(self.strkeLineStyle) {

case  StrikeLineStyleMiddle:

// 画线居中

lineRect =CGRectMake(0, rect.size.height/2, strikeWidth,1);

break;

case  StrikeLineStyleBottom:

// 画线居下

lineRect =CGRectMake(0, rect.size.height/2+ textSize.height/2, strikeWidth,1);

break;

default:

break;

}

}

if(self.strikeThroughEnabled){

CGContextRef  context =UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [self  strikeThroughColor].CGColor);

CGContextFillRect(context, lineRect);

}else{

CGContextRef  context =UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);

CGContextFillRect(context, lineRect);

}

}

在应用的类中:

BKStrikeLabel*label = [[BKStrikeLabel  alloc]init];

label.frame=CGRectMake(100,100,100,21);

label.font= [UIFont  systemFontOfSize:13];

label.text=@"¥1234567";

label.strkeLineStyle=StrikeLineStyleMiddle;//中间划线

label.strikeThroughEnabled=YES;

label.strikeThroughColor= [UIColor  redColor];

[self.view   addSubview:label];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容