UILabel - 自动换行文本
有什么办法可以根据需要提供标签自动换行文本吗? 我将换行符设置为自动换行,并且标签足够高,可以容纳两行,但它似乎只会在换行符上换行。 我是否必须添加换行符才能使其正确换行? 如果无法水平放置,我只想将其包裹起来。
Is there any way to have a label wordwrap text as needed? I have the line breaks set to word wrap and the label is tall enough for two lines, but it appears that it will only wrap on line breaks. Do I have to add line breaks to make it wrap properly? I just want it to wrap if it can't fit it in horizontally.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果将
numberOfLines
设置为 0(并且将标签设置为自动换行),则标签将自动换行并根据需要使用尽可能多的行。如果您在 IB 中编辑
UILabel
,则可以通过按 option+return 来输入多行文本以获得换行符 - <仅 kbd>return 即可完成编辑。If you set
numberOfLines
to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.If you're editing a
UILabel
in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.在 Swift 中你可以这样做:(
注意 lineBreakMode 常量的工作方式与 ObjC 中不同)
In Swift you would do it like this:
(Note that the way the lineBreakMode constant works is different to in ObjC)
UILabel
有一个属性lineBreakMode
,您可以根据您的要求进行设置。UILabel
has a propertylineBreakMode
that you can set as per your requirement.Xcode 10、Swift 4
也可以通过选择标签并使用属性检查器在情节提要上完成标签文本的包装。
线 = 0
换行 = 自动换行
Xcode 10, Swift 4
Wrapping the Text for a label can also be done on Storyboard by selecting the Label, and using Attributes Inspector.
Lines = 0
Linebreak = Word Wrap
Xcode 12.5.1,Swift 5。
我发现即使我设置了 Lines = 0 和 LineBreak = Word Wrap,它仍然没有换行长标签文本。 仔细检查 IB 中的标签约束(或您设置的任何位置)。
我发现有时 IB 会尝试修复约束设置并为前缘和后缘添加 >= 或 <= 约束。
此标签约束不会换行文本:
但这会:
请注意第一张图片中 Label.trailing 边缘上的 >=。 将其设置为= 并且文本应该换行。
Xcode 12.5.1, Swift 5.
I found that even though I had Lines = 0 and LineBreak = Word Wrap set, it still didn't wrap the long label text. Double check your label constraints in IB (or wherever you set them).
I found that sometimes IB tries to fix the constraint settings and adds a >= or <= constraint for leading and trailing edges.
This label constraint will not wrap the text:
But this will:
Notice the >= on the Label.trailing edge in the first picture. Set this to = and the text should wrap.