Setting text to fit the size of a UILabel and centre in SWIFT

天大地大妈咪最大 提交于 2019-12-12 08:26:39

问题


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.

This is my code:

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)

What am I doing wrong?


回答1:


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

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.

Swift 3:

questionsLabel.textAlignment = .center


来源:https://stackoverflow.com/questions/29265752/setting-text-to-fit-the-size-of-a-uilabel-and-centre-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!