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)
您可以在两个单词后面添加换行符 (
\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).尝试在第二个和第三个单词之间换行。请务必查看这篇文章,因为有时在获取标签时会出现一些问题根据字符串的来源识别换行符。
另一个简单的选择是使用两个 UILabels,一个用于前两个单词,第二个放置在其下方用于接下来的两个单词。
Try putting a line break between the second and third word. Make sure to checkout this post because sometimes there are some problems getting the label to recognize the line break based on the source of the string.
Another simple option would be to use two UILabels, one for the first two words and a second placed underneath it for the next two words.
我认为这篇文章可以帮助你,换行:如何添加换行符UILabel?
如果你想计算单词数(也许你的字符串是动态获取的),这个可以帮助你:什么是最不使用正则表达式来计算 NSString 中单词数的有效方法?
您应该将 UILabel 的 numberOfLines 属性设置为 0。(行数不受限制)。之后,我认为你应该计算 NSString 中的单词(使用 NSScanner 或 此方法),并在第二个单词后动态添加“\n”字符。
希望这有帮助,
杰里米.
I think this post could help you, for breaking lines : How to add line break for UILabel?
And this one could help you if you want to count words (maybe in case your string is obtained dynamically) : What is the most efficient way to count number of word in NSString without using regex?
You should set the numberOfLines property of your UILabel to 0. (unlimited number of lines). After that, I think you should count the words in your NSString (with NSScanner or this method), and add a "\n" character dynamically after the second word.
Hope this helps,
Jérémy.