Jim
Jim

Reputation: 9234

iPhone : Underline Text

Is there appeared easy way to underline text in iOS 4 ?? In IB maybe ? Thanks in advance...

Upvotes: 1

Views: 4067

Answers (4)

Mahesh
Mahesh

Reputation: 662

Sometimes i prefer to use UILabel as Underline with background of Underline color, no text, height 1 or 2 pixel and width as equal to Text to be underline...

Upvotes: 0

Ashok
Ashok

Reputation: 6244

NSMutableAttributedString/NSAttributedString allows you to create text with various rich attributes like font,color,type styles (including underline). For generic details follow this link..

Introduction to Attributed String Programming Guide

Specific to underline of text, this link may help.. Changing an Attributed String

Upvotes: 0

Jules
Jules

Reputation: 7223

As far as I know you cannot underline text.

You can "fake" it though by (for example) placing an UImageView or a regular View just underneath with the same color as your text. You can use strike-through etc, but cannot underline.

Edit: You could use this approach to underline your UILabel though. You could namely use a custom UILabel. So you could create some class like CUILabel that inherits UILabel and replace its drawRect method in the @implementation section with the following:

- (void)drawRect:(CGRect)rect {
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CGContextSetRGBStrokeColor(ctx, 0.0f/255.0f, 0.0f/255.0f, 255.0f/255.0f, 1.0f); // Your underline color
  CGContextSetLineWidth(ctx, 1.0f);

  UIFont *font = [UIFont systemFontOfSize:16.0f];
  CGSize constraintSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
  CGSize labelSize;
  labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];  

  CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
  CGContextAddLineToPoint(ctx, labelSize.width + 10, self.bounds.size.height - 1);

  CGContextStrokePath(ctx);

  [super drawRect:rect];  
}

Upvotes: 4

Alex Terente
Alex Terente

Reputation: 12036

Just subclass UILabel and in drawRect after you draw your text just draw an simple line under the text. Take a look at StrikeUILabel it have some bugs in it but you can start from that class.

Upvotes: 3

Related Questions