在xcode中加下划线的文字

时间:2012-09-14 11:38:49

标签: uitextfield underline

嘿我正在创建一个应用程序,要求文本视图的某些部分的文字加下划线。是否有一个简单的方法来做到这一点,如使其粗体和斜体或我必须制作和导入自定义字体?感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

这就是我所做的。它就像黄油一样。

1)将CoreText.framework添加到您的框架中。

2)在需要带下划线标签的类中导入<CoreText/CoreText.h>

3)编写以下代码。

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

答案 1 :(得分:1)

#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

答案 2 :(得分:0)

由于iOS 6.0 UILabelUITextFieldUITextView支持使用attributedText属性显示attributed strings

<强>用法:

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