如何在目标c iphone中加下划线? 是否有任何UILabel下划线文本的方法?
答案 0 :(得分:3)
子类UILabel
并覆盖drawRect
方法,如下所示。下划线将same text color
和text alignment
作为标签:
- (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];
}
答案 1 :(得分:2)
您可以从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];
}
答案 2 :(得分:1)
简单地说,UILabel中没有可用的高级格式。
如果您正在寻找的是一个链接,那么您最好使用UIWebView,并为其提供一些“自制HTML”,如“我的链接”。然后,您可以在webview的委托中单击webview。
答案 3 :(得分:0)
使用属性字符串:
NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"Your String"]
[attrString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:(NSRange){0,[attrString length]}];
然后覆盖标签 - (void)drawTextInRect:(CGRect)aRect并以如下方式呈现文本:
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);
或者更好的是,而不是覆盖只使用Olivier Halligon创建的OHAttributedLabel。他还支持自定义链接以及自定义颜色。