Lucas Bullen
Lucas Bullen

Reputation: 211

Make text underlined in xcode

Hey I'm making an app that requires a certain part of a text view's text to be underlined. is there a simple way to do this like for making it bold and italics or must i make and import a custom font? thanks for the help in advance!

Upvotes: 2

Views: 5361

Answers (3)

Durul Dalkanat
Durul Dalkanat

Reputation: 7435

#import <UIKit/UIKit.h>

@interface TextFieldWithUnderLine : UITextField

@end

#import "TextFieldWithUnderLine.h"

@implementation TextFieldWithUnderLine

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    //Get the current drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();
    //Set the line color and width
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 0.5f);
    //Start a new Path
    CGContextBeginPath(context);

    // offset lines up - we are adding offset to font.leading so that line is drawn right below the characters and still characters are visible.
    CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading + 4.0f);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading + 4.0f);

    //Close our Path and Stroke (draw) it
    CGContextClosePath(context);
    CGContextStrokePath(context);
}

@end

Upvotes: 1

Sana
Sana

Reputation: 557

This is what i did. It works like butter.

1) Add CoreText.framework to your Frameworks.

2) import <CoreText/CoreText.h> in the class where you need underlined label.

3) Write the following code.

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"My Messages"];
[attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                  value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                  range:(NSRange){0,[attString length]}];
self.myMsgLBL.attributedText = attString;
self.myMsgLBL.textColor = [UIColor whiteColor];

Upvotes: 2

DrummerB
DrummerB

Reputation: 40211

Since iOS 6.0 UILabel, UITextField and UITextView support displaying attributed strings using the attributedText property.

Usage:

NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:@"text"];
[aStr addAttribute:NSUnderlineStyleAttributeName value:NSUnderlineStyleSingle range:NSMakeRange(0,2)];
label.attributedText = aStr;

Upvotes: 0

Related Questions