我试图将文字设置为适合UILabel
的大小并且也居中。我是以编程方式执行此操作。这就是目前的情况:
正如您所看到的,文字离开了屏幕并且也没有居中。
这是我的代码:
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)
我做错了什么?
答案 0 :(得分:36)
questionsLabel.sizeToFit()
使框架适合文本的大小。你在寻找的是:
questionsLabel.adjustsFontSizeToFitWidth = true
这会更改字体大小以适合标签的宽度。 (但请注意,它只会缩小字体的大小。)
questionsLabel.textAlignment = NSTextAlignment.Center
将文本置于label.frame中心。所以,如果你这样做。并确保标签居中,宽度正确。你不应该做任何其他事情来使文本居中。
斯威夫特3:
questionsLabel.textAlignment = .center