UILabel文字换行/字符换行 [英] UILabel Word Wrap / Character Wrap
问题描述
我有一个UILabel,其中 lineBreakMode
设置为 UILineBreakModeWordWrap
。效果很好,除非我的文本较长且没有空格。在这种情况下,它不会包装较长的文本,而只会在到达UILabel框架的右端时将其剪切掉。在这种情况下,我如何告诉UILabel它应该只包裹在字符边界上[strong] (本质上等效于 UILineBreakModeCharacterWrap
设置,但仅适用于那些
预先感谢!
对于遇到相同问题的其他人,我最终使用 UITextView
代替了 UILabel
来解决。这是最佳的解决方案,其原因有两个:
-
不需要任何自定义行为即可确定文本是否包含空格和更改
UILabel
的换行模式到/从文字/字符换行。 -
更重要的是,在某种情况下,您可能会有普通的单词(要在单词边界上换行)和超长文本(需要在字符边界上换行)。缺少编写某种逻辑来在该超长文本(正确位置)中插入空格以强制进行假文字换行的方法,根据具体情况,我看不到任何处理文字和字符换行的方法,在一个
UILabel
中。UITextView
自动处理这种情况,并在必要时打破单词边界或字符边界。
有关我如何执行此操作的详细信息,我只有一行 UITextView
,已禁用编辑和滚动。我还设置了 .contentInset
来删除填充,使填充看上去像 UILabel
一样。然后,我使用 sizeWithFont:constrainedToSize:lineBreakMode:
方法确定渲染文本的框架,并调整 UITextView $的框架c $ c>从而使其完全适合文本。
希望这会有所帮助!
I have a UILabel with the lineBreakMode
set to UILineBreakModeWordWrap
. This works fine, except when I have a long slab of text with no spaces. In this case it does not wrap the long slab of text but instead just cuts it off once it reaches the right-hand end of the UILabel frame. How can I tell the UILabel that it should wrap on a character boundary in this situation only (essentially equivalent to the UILineBreakModeCharacterWrap
setting, but only for those long slabs of spaceless text).
Thanks in advance!
For anyone else having this same issue, I ended-up solving it by using a UITextView
instead of a UILabel
. This was the best solution for two reasons:
It doesn't require any custom behaviour to determine whether the text contains spaces and change the line break mode of the
UILabel
to/from word/character wrap.More importantly, there is an edge case whereby you may have normal words (that you want to wrap on word boundaries) plus extra long text (which you need to wrap on character boundaries). Short of writing some kind of logic to insert a space into that extra long text (at the correct position) to force a "fake word wrap" I can't see any way to handle wrapping on words and characters, depending on the situation, within the one
UILabel
. TheUITextView
handles this situation automatically, breaking on word boundaries or character boundaries as necessary.
For specifics on how I am doing this, I have a one line UITextView
with editing and scrolling disabled. I also set the .contentInset
to remove the padding making it look (to the unsuspecting eye) just like a UILabel
. I am then using the sizeWithFont:constrainedToSize:lineBreakMode:
method to determine the frame of the rendered text, and adjusting the frame of the UITextView
accordingly so that it exactly fits the text.
Hope that this helps!
这篇关于UILabel文字换行/字符换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!