【问题标题】:Setting text to fit the size of a UILabel and centre in SWIFT设置文本以适合 UILabel 的大小并在 SWIFT 中居中
【发布时间】:2015-03-25 20:20:28
【问题描述】:

我正在尝试将文本设置为适合 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)

我做错了什么?

【问题讨论】:

    标签: swift uiview uilabel


    【解决方案1】:
    questionsLabel.sizeToFit()
    

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

    questionsLabel.adjustsFontSizeToFitWidth = true
    

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

    questionsLabel.textAlignment = NSTextAlignment.Center
    

    将 label.frame 中的文本居中。因此,如果您执行上述操作。并确保标签居中,宽度正确。您无需执行任何其他操作即可使文本居中。

    斯威夫特 3:

    questionsLabel.textAlignment = .center
    

    【讨论】:

    • UILabel.sizeToFit()UITableView 的单元格中不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2012-02-06
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多