筆記->帶中(下)劃線的Label

創(chuàng)建個類繼承自UILabel

在.h中做如下操作

先在.h文件中設(shè)置個枚舉:

typedef NS_ENUM(NSInteger, StrikeLineStyle)? {

StrikeLineStyleMiddle,//中間劃線

StrikeLineStyleBottom//底部劃線

};

并在.h文件中設(shè)置3個公開的屬性,以便被調(diào)用:

@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);

}

}

在應(yīng)用的類中:

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];

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容