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
. The UITextView
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!