iOS 设置自定义间距的文字下划线

29 篇文章 0 订阅

网上看到很多用NSAttributedString的NSUnderlineStyleAttributeName来设置的,方法很简便,网上也很多,就不发了。

效果如下:

下划线和文字没有间隔,贴在一起的。

 

感觉不好看,而且后面项目还有一些需要用下划线的按钮,所以写了一个通用的UIButton子类,UnderlineTextButton

重写drawRect方法,用coregraphics的方法绘制下划线:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    CGRect titleFrame = self.titleLabel.frame;
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextSetStrokeColorWithColor(ctx, self.underLineColor.CGColor);
    CGContextSetLineWidth(ctx, 1.0f);
    
    CGContextMoveToPoint(ctx, CGRectGetMinX(titleFrame), CGRectGetMaxY(titleFrame));
    CGContextAddLineToPoint(ctx, CGRectGetMaxX(titleFrame), CGRectGetMaxY(titleFrame));
    
    CGContextStrokePath(ctx);
    
    [super drawRect:rect];
    
}

下划线一般和button的title等宽,在title的下面,有不同设计可以自行调整上面方法的Point位置

 

自定义下划线颜色属性 underLineColor,因为大部分时间与文本颜色一致,所以重写get方法

- (UIColor *)underLineColor{
    if (!_underLineColor) {
        _underLineColor = self.titleLabel.textColor;
    }
    return _underLineColor;
}

 

要用到时创建该子类即可

UnderlineTextButton *btn = [UnderlineTextButton buttonWithType:UIButtonTypeCustom];
btn.underLineColor = [UIColor grayColor];//不设置时下划线默认为和文字颜色相同

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值