IOS UIlabel 、UIButton添加下划线

时间:2023-03-08 17:11:13
IOS  UIlabel 、UIButton添加下划线

1.给UILabel 添加下划线

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
label.backgroundColor = [UIColor redColor];
label.numberOfLines = ;
NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"您的待办业务条fasdfasdfosadfjasdkljfklasjklfjasdlkjfklasdjklfjalskdjflkadsj"]];
NSRange contentRange = {,[content length]};
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
label.attributedText = content;
[self.view addSubview:label];

2. http://blog.csdn.net/chaoyuan899/article/details/38306141

方法一:

  1. NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"查看所有中奖记录"];
  2. NSRange strRange = {0,[str length]};
  3. [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
  4. [_awardDisplayBtn setAttributedTitle:str forState:UIControlStateNormal];

方法二:

HyperlinksButton.h

  1. #import <UIKit/UIKit.h>
  2. @interface HyperlinksButton : UIButton
  3. {
  4. UIColor *lineColor;
  5. }
  6. -(void)setColor:(UIColor*)color;
  7. @end

HyperlinksButton.m 

  1. #import "HyperlinksButton.h"
  2. @implementation HyperlinksButton
  3. - (id)initWithFrame:(CGRect)frame
  4. {
  5. self = [super initWithFrame:frame];
  6. if (self) {
  7. }
  8. return self;
  9. }
  10. -(void)setColor:(UIColor *)color{
  11. lineColor = [color copy];
  12. [self setNeedsDisplay];
  13. }
  14. - (void) drawRect:(CGRect)rect {
  15. CGRect textRect = self.titleLabel.frame;
  16. CGContextRef contextRef = UIGraphicsGetCurrentContext();
  17. CGFloat descender = self.titleLabel.font.descender;
  18. if([lineColor isKindOfClass:[UIColor class]]){
  19. CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor);
  20. }
  21. CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender+1);
  22. CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender+1);
  23. CGContextClosePath(contextRef);
  24. CGContextDrawPath(contextRef, kCGPathStroke);
  25. }
  26. @end

直接将这个类 copy 到工程中,,然后将需要加下划线的 Button 类名改为 HyperlinksButton就可以了,提供了 setColor: 这个接口,可以设置下划线颜色,代码很简单,不解释了。UILabel 同理可得。

示例结果:

IOS  UIlabel 、UIButton添加下划线

代码在这里