如何知道 UILabel 中显示的文本? [英] How to know the displayed text in UILabel?

查看:36
本文介绍了如何知道 UILabel 中显示的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个 UILabelsUIView,以便显示一个字符串.第一个UILabel是固定大小的,如果字符串太长,在这个UILabel中放不下,我想在第一个中显示我能做到的最大字符数UILabel,并在第二个 UILabel 中显示字符串的其余部分.

I have an UIView containing two UILabels, in order to display a string. The first UILabel has a fixed size, and if the string is too long and can't hold in this UILabel, I want to display the maximum characters I can in the first UILabel, and display the rest of the string in the second UILabel.

但要做到这一点,我必须知道第一个UILabel中显示的字符串的确切部分,这并不容易,因为字符串和换行符的随机性.

But to make this, I must know the exact part of the string displayed in the first UILabel, which is not easy because of the randomness of the string and the linebreaks.

那么,有没有办法只显示第一个 UILabel 中显示的文本,而不需要截断字符串的部分?

So, is there a way to get just the text displayed in the first UILabel, without the truncated part of the string?

推荐答案

if ([_infoMedia.description length] > 270) {
        NSRange labelLimit = [_infoMedia.description rangeOfString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(270, (_infoMedia.description.length - 270))];
        _descTop.text = [_infoMedia.description substringToIndex:labelLimit.location];
        _descBottom.text = [_infoMedia.description substringFromIndex:(labelLimit.location+1)];
} else {
            _descTop.text = _infoMedia.description;
            _descBottom.text = @"";
}

好的,这是一个迟到的答案,但也许它可以帮助某人.上面的代码大致是我在我的应用中使用的解决方案.

Okay that's a late answer but maybe it could help someone. The code above is approximatively the solution I used in my app.

_descTop 是我的第一个标签,_descBottom 是第二个标签.270 是一个常数,相当于略小于我的第一个标签 _descTop 中显示的平均最大字符数.我手工计算了它,尝试了许多不同的字符串,也许有更好的方法来做到这一点,但效果不错.

_descTop is my first label and _descBottom is the second label. 270 is a constant equivalent to a little less than the average maximum number of characters displayed in my first label, _descTop. I calculated it by hand, trying with many different strings, maybe there's a better way to do that but this worked not bad.

如果我要显示的字符串 (_infoMedia.description) 大于 270 个字符,我会隔离字符串中的前 270 个字符加上下一个单词的结尾(通过搜索下一个空格),如果270 个字符的限制会在单词中间剪切字符串.然后我把字符串的第一部分放在我的第一个标签中,第二部分放在第二个标签中.

If the string I want to display (_infoMedia.description) is larger than 270 characters, I isolate the first 270 characters plus the end of the next word in the string (by searching the next space), in the case where the 270 characters limit would cut the string in the middle of a word. Then I put the first part of the string in my first label, and the second part in the second label.

如果没有,我只将字符串的全局性放在第一个标签中.

If not, I only put the globality of the string in the first label.

我知道这是一个糟糕的解决方案,但它奏效了,而且我没有找到任何更好的方法来做到这一点.

I know that's a crappy solution, but it worked and I didn't found any better way to do that.

这篇关于如何知道 UILabel 中显示的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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