如何在Objective-C iPhone中给文本添加下划线?是否有一种方法可以在UILabel中给文本添加下划线?
如何在Objective-C iPhone中给文本添加下划线?是否有一种方法可以在UILabel中给文本添加下划线?
继承 UILabel
并重写 drawRect
方法如下。 下划线将具有与标签相同的文本颜色
和 文本对齐方式
:
- (void)drawRect:(CGRect)rect
{
if([[self.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length])
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);
CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];
// check text alignment
if(self.textAlignment == UITextAlignmentLeft) {
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, tmpSize.width, self.bounds.size.height - 1);
}else if(self.textAlignment == UITextAlignmentCenter) {
CGFloat startPoint = (self.frame.size.width - tmpSize.width) / 2;
CGContextMoveToPoint(ctx, startPoint, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, tmpSize.width + startPoint, self.bounds.size.height - 1);
}else if (self.textAlignment == UITextAlignmentRight) {
CGFloat startPoint = (self.frame.size.width - tmpSize.width);
CGContextMoveToPoint(ctx, startPoint, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, self.frame.size.width, self.bounds.size.height - 1);
}
CGContextStrokePath(ctx);
}
[super drawRect:rect];
}
你可以从 UILabel
中创建一个子类,并重写 drawRect
方法:
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, self.bounds.size.width, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
简单来说,在UILabel中没有可用的高级格式。
如果你想要的是一个链接,那么最好使用UIWebView,并将一些“自制HTML”提供给它,比如“My Link”。然后你可以在你的webview代理中处理对webview的点击。
NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"Your String"]
[attrString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:(NSRange){0,[attrString length]}];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
drawingRect = self.bounds;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, drawingRect);
textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);
CGPathRelease(path);
CFRelease(framesetter);
CTFrameDraw(textFrame, ctx);
CGContextRestoreGState(ctx);