当前位置: 代码迷 >> 综合 >> iOS在UILabel中间画删除线
  详细解决方案

iOS在UILabel中间画删除线

热度:29   发布时间:2024-01-20 18:47:05.0
1、自定义UILabel类:Label,此类继承UILabel类
(1)在Label.h中 

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


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


(2)在Label.m中 

- (void)drawTextInRect:(CGRect)rect

{

    [super drawTextInRect:rect];

    

    CGSize textSize = [[self text] sizeWithFont:[self font]];

    

    NSLog(@"______textSize = %@ , ______rect = %@",NSStringFromCGSize(textSize),NSStringFromCGRect(rect));

    

    CGFloat strikeWidth = textSize.width;

    

    CGRect lineRect;

    

    if ([self textAlignment] == NSTextAlignmentRight)

    {

        // 画线居中

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

        

        // 画线居下

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

    }

    else if ([self textAlignment] == NSTextAlignmentCenter)

    {

        // 画线居中

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

        

        // 画线居下

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

    }

    else

    {

        // 画线居中

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

        

        // 画线居下

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

    }

    

    if (self.strikeThroughEnabled)

    {

        CGContextRef context = UIGraphicsGetCurrentContext();

        

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

        

        CGContextFillRect(context, lineRect);

    }

}



(3)、使用:

- (void)viewDidLoad

{

    [super viewDidLoad];

    Label *label = [[Label alloc] initWithFrame:CGRectMake(100, 300, 200, 30)];

    label.text =@"Code4App $";

    label.backgroundColor = [UIColor yellowColor];

    label.textColor = [UIColor redColor];

    label.textAlignment = NSTextAlignmentCenter;


    [self.view addSubview:label];

}