在SWIFT中设置文本适应UILabel大小并居中

15

我正试图编写程序,使得一个UILabel的文本既适合其大小并且居中显示。当前的效果如下所示:

enter image description here

您可以看到,文本溢出了屏幕,并且也没有居中显示。

以下是我的代码:

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)

我错在哪里了?

1个回答

46
questionsLabel.sizeToFit()

使框架适应文本大小。您要查找的内容是:

questionsLabel.adjustsFontSizeToFitWidth = true

这会改变字体大小以适应标签的宽度。(但是请注意它只会缩小字体。)

questionsLabel.textAlignment = NSTextAlignment.Center

将文本居中显示在label.frame内。因此,如果按照上述方式操作并确保标签已居中且宽度正确,则无需进行其他任何操作即可居中文本。

Swift 3:

questionsLabel.textAlignment = .center

1
UILabel.sizeToFit()UITableView 的单元格中不起作用。 - user25
不在UICollectionView单元格中。 - ICL1901

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接