UILabel Text 加下划线

时间:2023-03-10 05:04:17
UILabel Text 加下划线
.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/, strikeWidth, );
} else if ([self textAlignment] == NSTextAlignmentCenter) {
lineRect = CGRectMake(rect.size.width/ - strikeWidth/, rect.size.height/, strikeWidth, );
} else {
lineRect = CGRectMake(, rect.size.height/, strikeWidth, );
} if (_isEnabled) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context, lineRect);
}
} // 调用 CustomLabel *_label;
_label = [[CustomLabel alloc]initWithFrame:CGRectMake(, , , )];
_label.text = @"这是一个多么美好的世界啊";
_label.backgroundColor = [UIColor clearColor];
_label.isEnabled = YES;
[_label sizeToFit];
_label.textColor = [UIColor redColor];
[self.view addSubview:_label];