将NSString分成几行(以适合所需的宽度) [英] Breaking NSString into lines (to fit desired width)

查看:38
本文介绍了将NSString分成几行(以适合所需的宽度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将NSString分成几行以适合所需的宽度(因为它会发生在 sizeWithFont:constrainedToSize:内部).是否有比猜测 sizeWithFont 中的中断位置更好的方法呢?

I'm trying to get a NSString broken into lines to fit a desired width (as it would happen inside sizeWithFont:constrainedToSize:). Is there a better way to do this than guessing where the breaks would happen in sizeWithFont?

推荐答案

如果 NSLayoutManager 确实不可用,您可能会遇到效率更低的解决方案:从字符串的第一个单词开始,附加随后的每个单词,并在结果字符串上使用 sizeWithFont:(等)方法.当返回的 CGSize 的高度发生变化时,最近附加的单词就是引起换行的单词,因此您可以在此处拆分字符串.

If NSLayoutManager is indeed unavailable, you may be stuck with a more inefficient solution: starting with the first word of the string, appending each subsequent word and using the sizeWithFont:(etc.) method on the resulting string. When the height of the returned CGSize changes, the most recently appended word was the one that caused the line break, and you can thus split the string there.

这篇关于将NSString分成几行(以适合所需的宽度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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