Make text underlined in xcode

风格不统一 提交于 2019-12-23 22:07:11

问题


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!


回答1:


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];



回答2:


#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



回答3:


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;


来源:https://stackoverflow.com/questions/12423776/make-text-underlined-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!