如何截断基于图形宽度的NSString? [英] How to truncate an NSString based on the graphical width?

查看:227
本文介绍了如何截断基于图形宽度的NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UILabel中,有使用不同截断技术(UILineBreakMode)截断标签的功能。在NSString UIKit添加中,有一个类似的绘制字符串的功能。

In UILabel there's functionality to truncate labels using different truncation techniques (UILineBreakMode). In NSString UIKit Additions there is a similar functionality for drawing strings.

但是,我没有找到方法来访问实际截断的字符串。是否有任何其他方法可以基于给定字体的(图形)宽度获取截断的字符串?

However, I found no way to access the actual truncated string. Is there any other way to get a truncated string based on the (graphical) width for a given font?

我想使用NSString类别:

I'd like to have a category on NSString with this method:

-(NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode


推荐答案

一个选项是尝试不同的大小循环,右宽度。也就是说从完整的字符串开始,如果它比你需要的更宽,用省略号字符替换最后两个字符。

One option is trying different sizes by looping until you get the right width. I.e. start with the full string, if that's wider than what you need, replace the last two characters with an ellipsis character. Loop until it's narrow enough.

如果你认为你将使用长字符串,你可以通过二分搜索的方式去截取点,使它更快一点。

If you think you'll be working with long strings, you can binary search your way towards the truncation point to make it a bit faster.

这篇关于如何截断基于图形宽度的NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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