Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underline text in UIlabel

How can I underline a text that could be multiple lines of string? I find some people suggest UIWebView, but it is obviously too heavy a class for just text rendering.

My thoughts was to figure out the start point and length of each string in each line. And draw a line under it accordingly.

I meet problems at how to figure out the length and start point for the string.

I tried to use -[UILabel textRectForBounds:limitedToNumberOfLines:], this should be the drawing bounding rect for the text right? Then I have to work on the alignment? How can I get the start point of each line when it is center-justified and right justified?

like image 289
semix Avatar asked Apr 26 '10 05:04

semix


People also ask

How do you underline text in IOS?

To underline a text message on an iPhone you need to first make sure the option is enabled. Once the feature is enabled you long hold over the text you want to underline. Then tap the button showing a “U” which stands for underline. This will underline the highlighted portion of your text message.

How do I underline a label in Xcode?

Now a a small text editor will be visible under the font of the label. Select the text of the label, right click and change the font to 'underline'.


2 Answers

You may subclass from UILabel and override drawRect method:

- (void)drawRect:(CGRect)rect {     CGContextRef ctx = UIGraphicsGetCurrentContext();     CGContextSetRGBStrokeColor(ctx, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f); // RGBA     CGContextSetLineWidth(ctx, 1.0f);      CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);     CGContextAddLineToPoint(ctx, self.bounds.size.width, self.bounds.size.height - 1);      CGContextStrokePath(ctx);      [super drawRect:rect];   } 

UPD:
As of iOS 6 Apple added NSAttributedString support for UILabel, so now it's much easier and works for multiple lines:

NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}; myLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Test string"                                                           attributes:underlineAttribute]; 

If you still wish to support iOS 4 and iOS 5, I'd recommend to use TTTAttributedLabel rather than underline label manually. However if you need to underline one-line UILabel and don't want to use third-party components, code above would still do the trick.

like image 86
kovpas Avatar answered Oct 08 '22 23:10

kovpas


In Swift:

let underlineAttriString = NSAttributedString(string: "attriString",                                           attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]) label.attributedText = underlineAttriString 
like image 38
ytll21 Avatar answered Oct 08 '22 22:10

ytll21