本文介绍了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. Can anybody help me on this?

我试图使用 - [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?

我是新来的,所以先谢谢你。

I am new here, so thank you in advance.

推荐答案

您可以从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,我建议使用而不是手动标注下划线。但是,如果你需要为一行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中的下划线文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 05:39
查看更多