设置文本以适应 UILabel 的大小并在 SWIFT 中居中 [英] Setting text to fit the size of a UILabel and centre in SWIFT

查看:87
本文介绍了设置文本以适应 UILabel 的大小并在 SWIFT 中居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本设置为适合 UILabel 的大小并且居中.我正在以编程方式执行此操作.这是目前的样子:

I'm trying to set text to fit the size of a UILabel and also be centred. I am doing this programmatically. This is what it looks like currently:

如您所见,文本不在屏幕上,也没有居中.

As you can see, the text is going off the screen and is also not centred.

这是我的代码:

let questions = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac faucibus tellus."

questionsLabel = UILabel(frame: CGRectMake(10, 10, questionsView.frame.size.width - 20, 80))
questionsLabel.text = questions
questionsLabel.font = UIFont(name: Font.FuturaMedium, size: 25)
questionsLabel.sizeToFit()
questionsLabel.numberOfLines = 0
questionsLabel.textAlignment = NSTextAlignment.Center
questionsView.addSubview(questionsLabel)

我做错了什么?

推荐答案

questionsLabel.sizeToFit()

使框架适合文本的大小.您正在寻找的是:

Makes the frame fit the size of the text. What you are looking for is:

questionsLabel.adjustsFontSizeToFitWidth = true

这会更改字体大小以适合标签的宽度.(但请注意,它只会缩小字体.)

This changes the font size to fit the width of the label. (However, do note that it will only downsize the font.)

questionsLabel.textAlignment = NSTextAlignment.Center

将 label.frame 中的文本居中.所以如果你做到了以上.并确保标签居中,并且宽度正确.您无需执行任何其他操作即可将文本居中.

Centers the text within the label.frame. So if you do the above. And make sure the label is centered, and it's width is correct. You shouldn't have to do anything else to center the text.

斯威夫特 3:

questionsLabel.textAlignment = .center

这篇关于设置文本以适应 UILabel 的大小并在 SWIFT 中居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆