How to underline text in objective c iphone?? Is there any method for underline text of UILabel??
Subclass UILabel and override drawRect method as below. Underline will have the same text color and text alignment as the label:
- (void)drawRect:(CGRect)rect
{
if([[self.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);
CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];
// check text alignment
if(self.textAlignment == UITextAlignmentLeft) {
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, tmpSize.width, self.bounds.size.height - 1);
}else if(self.textAlignment == UITextAlignmentCenter) {
CGFloat startPoint = (self.frame.size.width - tmpSize.width) / 2;
CGContextMoveToPoint(ctx, startPoint, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, tmpSize.width + startPoint, self.bounds.size.height - 1);
}else if (self.textAlignment == UITextAlignmentRight) {
CGFloat startPoint = (self.frame.size.width - tmpSize.width);
CGContextMoveToPoint(ctx, startPoint, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, self.frame.size.width, self.bounds.size.height - 1);
}
CGContextStrokePath(ctx);
}
[super drawRect:rect];
}
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With