如何从UILabel的第n行获取文本/字符串? [英] How to get text / String from nth line of UILabel?

查看:116
本文介绍了如何从UILabel的第n行获取文本/字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以从UILabel中的给定行中获取(或简单地显示)文本?

Is there an easy way to get (or simply display) the text from a given line in a UILabel?

我的UILabel正确显示了我的文本并对其进行了漂亮的布局,但是偶尔我需要能够仅显示某些行,但是显然我需要知道UILabel如何放置一切来做到这一点.

My UILabel is correctly displaying my text and laying it out beautifully but occasionally I need to be able to just show certain lines but obviously I need to know how UILabel has positioned everything to do this.

我知道可以很容易地用子字符串完成此操作,但是我需要知道该行的起点和终点.

I know this could easily be done with a substring but I'd need to know the start and end point of the line.

或者,如果UILabel的框架存在某种偏移,我可以滚动UILabel并隐藏我不想看到的其余内容.

Alternatively I could scroll the UILabel if there was some kind of offset to the UILabel's frame and hide the rest of the content I didn't want to see.

我无法发现任何可以轻松完成此操作的内容.有人有什么好主意吗?

I've not been able to uncover anything that shows how this could be done easily. Anyone got any good ideas?

谢谢

iphaaw

推荐答案

我不认为有这样做的本机方法(例如"takethenline"方法).
我可以找出一个棘手的解决方案,但不确定是否是最佳解决方案.
您可以将标签分成单词数组.
然后,您可以循环数组并检查文本高度,直到像这样的单词为止:

I don't think there's a native way for doing this (like a "takethenline" method).
I can figure out a tricky solution but I'm not sure is the best one.
You could split your label into an array of words.
Then you could loop the array and check the text height until that word like this:

NSString *texttocheck;
float old_height = 0;
int linenumber = 0; 

for (x=0; x<[wordarray lenght]; x++) {
    texttocheck = [NSString stringWithFormat:@"%@ %@", texttocheck, [wordarray objectAtIndex:x]];

    float height = [text sizeWithFont:textLabel.font
                    constrainedToSize:CGSizeMake(textLabel.bounds.size.width,99999) 
                        lineBreakMode:UILineBreakModeWordWrap].height;

    if (old_height < height) {
        linenumber++;
    }
}

如果高度发生变化,则表示单词前有换行符.
我现在无法检查语法是否正确编写,因此您必须自己检查它.

If height changes, it means there's a line break before the word.
I can't check if the syntax is written correctly now, so you have to check it yourself.

这篇关于如何从UILabel的第n行获取文本/字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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