2012-09-14 182 views
2

嘿,我正在制作一个应用程序,要求将文本视图文本的某个部分加下划线。有没有一种简单的方法来做到这一点,如使它粗体和斜体,或者我必须制作和导入自定义字体?我在这里先向您的帮助表示感谢!在xcode中使文字下划线

回答

0

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

用法:

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

感谢的人生病让这个尝试 –

+0

东西是不工作;这里是我的代码,你看到任何突出的错误? NSMutableAttributedString * aStr = [[NSMutableAttributedString alloc] initWithString:BookTitle.text]; [aStr addAttribute:NSUnderlineStyleAttributeName value:NSUnderlineStyleSingle range:NSMakeRange(0,2)]; BookTitle.attributedText = aStr; –

+0

其中BookTitle是一个textFeild –

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