創(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];
完