I often need to underline the text of an UILabel in my iOS projects in a specific way. Here's how I've done it.
Create a subclass of UILabel, call it e.g. RGUnderlineText and overridde the
- (void)drawRect:(CGRect)rect method.
- (void)drawRect:(CGRect)rect {
/* draw a dotted line at the bottom of the UILabel */
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0f, 0.f, 0.0f, 1.0f);
CGFloat lengths[] = {1,1};
CGContextSetLineDash(context, 0, lengths, 2);
CGContextSetLineWidth(context, 1.0f);
CGContextMoveToPoint(context, 0, self.bounds.size.height - 4);
CGContextAddLineToPoint(context, self.bounds.size.width,
self.bounds.size.height - 4);
CGContextStrokePath(context);
/* draw the typical UILabel now */
[super drawRect:rect];
}
The drawRect code draws a dotted line at the bottom of the UILabel and calls super to get the normal text drawn. You can of course adjust the code/drawing to your needs.
In Interface Builder drag an UILabel element from the Library on a view and set the class to your new subclass of UILabel, e.g. RGUnderlineText in my case. That's it.
The sample code is available as a XCode project at bitbucket.org.
Here's a screenshot of the final result: