label里面的文字换行_UILabel文字换行/字符换行

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值