UIlabel 中的下划线文本 [英] Underline text in UIlabel

查看:25
本文介绍了UIlabel 中的下划线文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为可能是多行字符串的文本加下划线?我发现有些人建议使用 UIWebView,但对于文本渲染来说,它显然太重了.

How can I underline a text that could be multiple lines of string? I find some people suggest UIWebView, but it is obviously too heavy a class for just text rendering.

我的想法是找出每行中每个字符串的起点和长度.并相应地在其下方画一条线.

My thoughts was to figure out the start point and length of each string in each line. And draw a line under it accordingly.

我在如何计算字符串的长度和起点时遇到问题.

I meet problems at how to figure out the length and start point for the string.

我尝试使用-[UILabel textRectForBounds:limitedToNumberOfLines:],这应该是文本的绘图边界矩形吧?然后我必须在对齐上工作?中心对齐和右对齐时如何获取每条线的起点?

I tried to use -[UILabel textRectForBounds:limitedToNumberOfLines:], this should be the drawing bounding rect for the text right? Then I have to work on the alignment? How can I get the start point of each line when it is center-justified and right justified?

推荐答案

你可以从 UILabel 子类化并覆盖 drawRect 方法:

You may subclass from UILabel and override drawRect method:

- (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];  
}

<小时>

UPD:
从 iOS 6 开始,Apple 为 UILabel 添加了 NSAttributedString 支持,因此现在它更容易并且适用于多行:


UPD:
As of iOS 6 Apple added NSAttributedString support for UILabel, so now it's much easier and works for multiple lines:

NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Test string" 
                                                         attributes:underlineAttribute];

如果您仍然希望支持 iOS 4 和 iOS 5,我建议您使用 TTTAttributedLabel 而不是比手动下划线标签.但是,如果您需要在一行 UILabel 下划线并且不想使用第三方组件,上面的代码仍然可以解决问题.

If you still wish to support iOS 4 and iOS 5, I'd recommend to use TTTAttributedLabel rather than underline label manually. However if you need to underline one-line UILabel and don't want to use third-party components, code above would still do the trick.

这篇关于UIlabel 中的下划线文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆