问题描述
我正在开发一个带有 Storyboard 的 Swift 项目,我希望将文本包装在标签中.在我没有使用 Storyboard 的旧 Objective-C 版本中,我使用了以下设置并且一切正常.
I am working on a Swift project with Storyboards where I want text to wrap in a label. In the old Objective-C version where I did not use a Storyboard I used the following settings and things worked perfectly.
这里是 Swift 的设置
Here are the settings for Swift
我一直在阅读有关首选宽度设置的潜在自动布局问题.我目前将它们设置为自动布局,并且标签本身的宽度设置为 560.我添加了一个约束以使标签与尾随的超级视图保持 20 像素,虽然我认为这可行,但我仍然无法获取文本裹.尺寸设置如下.
I have been reading about the potential auto layout issues with preferred width settings. I currently have them set to auto layout and the label itself is set to a width of 560. I've added a constraint to keep the label 20 pixels from the trailing superview and while I thought this would work I still cannot get the text to wrap. The dimension settings are below.
有人可以解释如何让文本换行吗?
Can someone explain how to get the text to wrap?
推荐答案
首先,好消息:您已将标签设置为 2 行和自动换行.所以它可以换行.太棒了.
First, the good news: You have set the label to 2 lines and Word Wrap. So it can wrap. Excellent.
现在您必须确保标签足够高.要么给它no高度限制,要么给它一个足够大的高度限制,让它可以容纳两条线.
Now you must make sure the label is tall enough. Either give it no height constraint, or give it a big enough height constraint that it can accommodate two lines.
最后,你必须限制它的宽度.这就是导致文本换行的原因.如果你不限制标签的宽度,它只会继续向右增长,可能会继续离开屏幕.标签宽度的限制会阻止这种向右增长并导致文本换行(并且标签会向下增长).
Finally, you must limit its width. This is what causes the text to wrap. If you don't limit the label's width, it will just keep growing rightward, potentially continuing off the screen. The limit on the label's width stops this rightward growth and causes the text to wrap (and the label to grow downward instead).
您可以通过多种方式限制宽度.你可以有一个实际的宽度限制.或者你可以有一个前导约束和一个尾随约束,对于相对不动的东西,比如超级视图.还有第三种方法:在尺寸检查器(您也显示,在问题的右下角)上,设置首选宽度(显示在尺寸检查器的顶部):这是宽度,在所有其他条件相同的情况下,标签将停止向右增长,而是包裹并向下增长.
You can limit width in several ways. You can have an actual width constraints. Or you can have a leading constraint and a trailing constraint, to something relatively immovable, such as the superview. And there is a third way: on the Size inspector (which you do also show, at the bottom right of your question), set the Preferred Width (it is shown at the top of the Size inspector): this is the width at which, all other things being equal, the label will stop growing to the right and wrap and grow down instead.
这篇关于UILabel 文本不换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!