iOS>> UILabel:如何创建与字数统计相关的行分隔符
我使用在 IB 中定义的 UILabel 包括 2 行
文本本身来自代码:
[self.myUILabel setText:[someDictionaryThatHoldsNSStrings objectForKey:someDictionaryKey]];
字符串中始终有 4 个单词;我想确保在任何情况下第一行中始终有 2 个单词,第二行中始终有 2 个单词,但使用自动换行并不能解决问题,因为单词的长度根据字符串而有所不同。
如何定义 UILabel 将始终在第一行保留 2 个单词,在第二行保留 2 个单词?
I use a UILabel that is defined in IB as including 2 lines
The text itself is coming from the code:
[self.myUILabel setText:[someDictionaryThatHoldsNSStrings objectForKey:someDictionaryKey]];
There are always 4 words in the string; I want to make sure that in any case there will always be 2 words in the first line and 2 words in the second line but using Word Wrap doesn't do the trick since the length of the word is deferent depending on the strings.
How do I define that the UILabel will always hold 2 words in the first line and 2 words in the second line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
我认为这篇文章可以帮助你,换行:如何添加换行符UILabel?
如果你想计算单词数(也许你的字符串是动态获取的),这个可以帮助你:什么是最不使用正则表达式来计算 NSString 中单词数的有效方法?
您应该将 UILabel 的 numberOfLines 属性设置为 0。(行数不受限制)。之后,我认为你应该计算 NSString 中的单词(使用 NSScanner 或 此方法),并在第二个单词后动态添加“\n”字符。
希望这有帮助,
杰里米.
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以在两个单词后面添加换行符 (
\n
) 并将其显示在标签中,而无需更改标签的大小,而不是尝试查找单词的长度和单词的大小或lineBreakMode。使用上面的方法来格式化字符串。代码似乎太大了。我这样写只是为了让大家能够理解。您仍然可以根据需要简化它。
并确保标签的 numberOfLines 设置为
2
(标签仅显示两行)或0
(动态行数)。Instead of trying to find the length of the words and finding the size for the words, you can add a newline(
\n
) character after the two words and display it in the label without altering the label's size or lineBreakMode.Use the above method to format the string. The code seems too big. I write it in this way just to make it understandable. You can still simplify it as you want.
And make sure the numberOfLines of label set to
2
(label will show only two lines) or0
(for dynamic number of lines).