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. Can anybody help me on this?
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?
I am new here, so thank you in advance.
I've combined some of provided answers, to create better (at least for my requirements) UILabel subclass, which supports:
https://github.com/GuntisTreulands/UnderLineLabel
An enhanced version of the code of Kovpas (color and line size)
As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.
Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.
You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.
Look up the UIKit additions to NSString:
NSUnderlineStyleAttributeName which takes an NSNumber (where 0 is no underline) can be added to an attribute dictionary. I don't know if this is any easier. But, it was easier for my purposes.
Here is the easiest solution which works for me without writing additional codes.