IOS之UILabel添加下划线

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)