IOS之UILabel添加下划线

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);
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值