UILabel添加下划线的方式有多种方法,这里介绍两种常用的方法.
1. 利用UILabel的属性来添加下划线
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:@"This is a under line label"];
NSRange contentRange = {0, [content length]};
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
label.attributedText = content;
[self.view addSubview:label];2. 重绘UILabel添加下划线
创建一个基于UILabel的类,命名为UnderLineLabel.
在UnderLineLabel中重绘Label,添加如下代码:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGSize fontSize =[self.text sizeWithFont:self.font
forWidth:self.frame.size.width
lineBreakMode:NSLineBreakByTruncatingTail];
CGContextSetStrokeColorWithColor(ctx, self.textColor.CGColor); // set as the text's color
CGContextSetLineWidth(ctx, 2.0f);
CGPoint leftPoint = CGPointMake(0,
self.frame.size.height);
CGPoint rightPoint = CGPointMake(self.frame.size.width,
self.frame.size.height);
CGContextMoveToPoint(ctx, leftPoint.x, leftPoint.y);
CGContextAddLineToPoint(ctx, rightPoint.x, rightPoint.y);
CGContextStrokePath(ctx);
}
接下来,我们只需要用UnderLineLabel来创建Label即可.
iOS实现UILabel添加下划线的两种方法
本文介绍了在iOS开发中为UILabel添加下划线的两种常见方法:通过利用UILabel的属性以及通过创建自定义UnderLineLabel类并重绘来实现下划线效果。详细步骤包括在自定义类中添加重绘代码,并展示如何使用UnderLineLabel创建带下划线的Label。
1万+

被折叠的 条评论
为什么被折叠?



