.h文件
#import <Foundation/Foundation.h>

@interface CustomLabel : UILabel
{
    BOOL _isEnabled;
}

@property (nonatomic ) BOOL isEnabled;

@end

.m文件
#import "CustomLabel.h"

@implementation CustomLabel

@synthesize isEnabled = _isEnabled;

- (void)drawTextInRect:(CGRect)rect{
    [super drawTextInRect:rect];
    
    CGSize textSize = [[self text] sizeWithFont:[self font]];
    CGFloat strikeWidth = textSize.width;
    CGRect lineRect;
    
    if ([self textAlignment] == NSTextAlignmentRight) {
        lineRect = CGRectMake(rect.size.width - strikeWidth, rect.size.height/2, strikeWidth, 1);
    } else if ([self textAlignment] == NSTextAlignmentCenter) {
        lineRect = CGRectMake(rect.size.width/2 - strikeWidth/2, rect.size.height/2, strikeWidth, 1);
    } else {
        lineRect = CGRectMake(0, rect.size.height/2, strikeWidth, 1);
    }
    
    if (_isEnabled) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextFillRect(context, lineRect);
    }
}

// 调用

CustomLabel *_label;
 _label = [[CustomLabel alloc]initWithFrame:CGRectMake(50, 100, 0, 40)];
 _label.text = @"这是一个多么美好的世界啊";
 _label.backgroundColor = [UIColor clearColor];
 _label.isEnabled = YES;
 [_label sizeToFit];
  _label.textColor = [UIColor redColor];
 [self.view addSubview:_label];

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2021-05-18
  • 2022-12-23
  • 2021-04-19
  • 2022-01-13
  • 2021-09-27
猜你喜欢
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
  • 2021-05-02
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案