当前位置: 代码迷 >> 综合 >> iOS 给UILabel添加下划线
  详细解决方案

iOS 给UILabel添加下划线

热度:56   发布时间:2024-01-20 18:37:34.0

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.fontforWidth:self.frame.size.widthlineBreakMode:NSLineBreakByTruncatingTail];CGContextSetStrokeColorWithColor(ctx, self.textColor.CGColor);  // set as the text's colorCGContextSetLineWidth(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即可.