xcode 如何使 UILabel 调整大小以适合文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39240041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make UILabel resize to fit text
提问by zorro2b
I have a UILabel that I have layed out in a storyboard centred in the view. It has some initial text "tap to login".
我有一个 UILabel,我已经将它放置在以视图为中心的故事板中。它有一些初始文本“点击登录”。
I am changing the value of the label to be the user's name once they have logged in. Once I do this, the label is no longer centered as the UILabel has not changed size.
我正在将标签的值更改为用户登录后的名称。一旦我这样做,标签不再居中,因为 UILabel 没有改变大小。
How can I do this with autolayout in interface builder?
如何在界面构建器中使用自动布局来做到这一点?
回答by balkaran singh
see this scrrenshot
看这个截图
1 first select your label width constraint
1 首先选择你的标签宽度约束
2 set the relation Greater than or equal
2 设置关系大于等于
3 set the default constant value here i set it 10
3 这里设置默认常量值我设置为 10
when you change the label text it change the size of label according to its text. hope it's help :)
当您更改标签文本时,它会根据其文本更改标签的大小。希望它有帮助:)
回答by Rakshith Nandish
Iam guessing the label is not getting height and width, consider giving those constraints and then when your text changes use this method to determine the height and width:
我猜标签没有获得高度和宽度,请考虑提供这些约束,然后当您的文本更改时使用此方法来确定高度和宽度:
func labelSizeWithString(text: String, maxWidth : CGFloat,numberOfLines : Int) -> CGRect{
let label = UILabel(frame: CGRectMake(0, 0, maxWidth, CGFloat.max))
label.numberOfLines = numberOfLines
label.text = text
label.sizeToFit()
return label.frame
}
回答by Randall Wang
You can set the UILabel
frame.width
bigger, maybe the same width as the screen.
您可以设置UILabel
frame.width
更大的,也许与屏幕的宽度相同。
Then you set the
然后你设置
label.textAlignment = NSTextAlignmentCenter
label.textAlignment = NSTextAlignmentCenter
回答by Pavankumar
1.showing initial text to label
2.After pressing button changing text, that showing in middle of screen 3.Look at constraints third image, two constraints given 1.top to view 2.horizontally middle in container
1.显示初始文本到标签 2.按下按钮更改文本后,显示在屏幕中间 3.查看约束第三张图像,给出两个约束 1.top 以查看 2.horizontally 在容器中的中间
Another thing if u given fixed width for the label,change relation as more than equal.[Click width constraint ,see right side top there change the relation