【发布时间】:2012-09-07 13:47:45
【问题描述】:
嘿,我正在制作一个需要在文本视图文本的特定部分加下划线的应用。有没有一种简单的方法可以让它变成粗体和斜体,或者我必须制作和导入自定义字体?提前感谢您的帮助!
【问题讨论】:
标签: uitextfield underline
嘿,我正在制作一个需要在文本视图文本的特定部分加下划线的应用。有没有一种简单的方法可以让它变成粗体和斜体,或者我必须制作和导入自定义字体?提前感谢您的帮助!
【问题讨论】:
标签: uitextfield underline
#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
【讨论】:
这就是我所做的。它就像黄油一样工作。
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];
【讨论】:
从 iOS 6.0 开始,UILabel、UITextField 和 UITextView 支持使用属性文本属性显示 attributed strings。
用法:
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:@"text"];
[aStr addAttribute:NSUnderlineStyleAttributeName value:NSUnderlineStyleSingle range:NSMakeRange(0,2)];
label.attributedText = aStr;
【讨论】: