1

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

Jim
  • 8,874
  • 16
  • 68
  • 125

4 Answers4

4

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];  
}
Jules
  • 7,148
  • 6
  • 26
  • 50
3

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.

Alex Terente
  • 12,006
  • 5
  • 51
  • 71
0

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...

Mahesh
  • 662
  • 2
  • 11
  • 30
0

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

Ashok
  • 6,224
  • 2
  • 37
  • 55