首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在UIlabel中给文本加下划线

在UIlabel中给文本加下划线
EN

Stack Overflow用户
提问于 2010-04-26 13:33:19
回答 17查看 127.2K关注 0票数 92

如何为可能是多行字符串的文本加下划线?我发现有些人建议使用UIWebView,但它显然是一个太重的类,不能只渲染文本。

我的想法是计算出每行中每个字符串的起点和长度。并相应地在它下面画一条线。

我遇到了如何计算字符串的长度和起始点的问题。

我尝试使用-[UILabel textRectForBounds:limitedToNumberOfLines:],这应该是文本的绘图边框,对吧?那我还得做对齐吗?当每一行都是居中对齐和右对齐时,我如何获得每行的起点?

EN

回答 17

Stack Overflow用户

发布于 2014-11-22 16:51:34

在Swift中:

let underlineAttriString = NSAttributedString(string: "attriString",
                                          attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
label.attributedText = underlineAttriString
票数 52
EN

Stack Overflow用户

发布于 2013-10-28 16:47:47

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

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

2)在需要下划线标签的类中导入。

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];
票数 38
EN

Stack Overflow用户

发布于 2012-04-11 20:08:01

使用属性字符串:

NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"Your String"]
[attrString addAttribute:(NSString*)kCTUnderlineStyleAttributeName 
                   value:[NSNumber numberWithInt:kCTUnderlineStyleSingle] 
                   range:(NSRange){0,[attrString length]}];

然后覆盖label - (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

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2711297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档