The UI label or uibutton developed by IOS is underlined

Time:2022-5-26

The UI label or uibutton developed by IOS is underlined

       This paper mainly introduces the implementation method of underlined links of uilable and uibutton in IOS and the download of source code. If you need to develop IOS applications, you can refer to the following:

Method 1:

Nsmutableattributedstring * STR = [[nsmutableattributedstring alloc] initwithstring: @ "view all winning records"]; 
NSRange strRange = {0,[str length]}; 
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange]; 
[_awardDisplayBtn setAttributedTitle:str forState:UIControlStateNormal];

Method 2:

HyperlinksButton.h


#import <UIKit/UIKit.h> 
 
@interface HyperlinksButton : UIButton 
{ 
  UIColor *lineColor; 
} 
-(void)setColor:(UIColor*)color; 
@end 

HyperlinksButton.m 
[objc] view plain copy print?
#import "HyperlinksButton.h" 
 
@implementation HyperlinksButton 
 
- (id)initWithFrame:(CGRect)frame 
{ 
  self = [super initWithFrame:frame]; 
  if (self) { 
     
  } 
  return self; 
} 
 
-(void)setColor:(UIColor *)color{ 
  lineColor = [color copy]; 
  [self setNeedsDisplay]; 
} 
 
 
- (void) drawRect:(CGRect)rect { 
  CGRect textRect = self.titleLabel.frame; 
  CGContextRef contextRef = UIGraphicsGetCurrentContext(); 
   
  CGFloat descender = self.titleLabel.font.descender; 
  if([lineColor isKindOfClass:[UIColor class]]){ 
    CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor); 
  } 
   
  CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender+1); 
  CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender+1); 
   
  CGContextClosePath(contextRef); 
  CGContextDrawPath(contextRef, kCGPathStroke); 
} 
@end 

Directly copy this class into the project, and then change the button class name that needs to be underlined to hyperlinksbutton. SetColor: this interface is provided to set the underline color. The code is very simple and will not be explained. Uilabel can be obtained in the same way.

Example results:

Source code download address: https://github.com/chaoyuan899/HyperlinksButton#how -to-use

Download the source code of this website:http://xiazai.jb51.net/201707/yuanma/HyperlinksButton-master(jb51.net).rar

Thank you for reading, hope to help you, thank you for your support to this site!