在 viewcontroller 中有自动调整文本大小

Have autosizing text in a viewcontroller

有人能告诉我为什么这段代码不能自动调整 descLabel 中的文本大小吗?我尝试将 numberOfLines 设置为 0 并设置了 lineBreakMode 但这几乎无法解决我的问题。这种方法在 ViewController 中是不可能的还是我做错了什么?

class SingleEventViewController: UIViewController {

var thisEvent: Event
var eventDescription: String?

let descLabel: UILabel = {
    let label = UILabel()
    label.font = UIFont.systemFont(ofSize: 16)
    label.text = "Beschreibung"
    label.textColor = .black
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    return label
}()  

let participateButton: UIButton = {
    let button = UIButton()
    button.backgroundColor = CalendarSettings.Colors.buttonBG
    button.setTitle("Teilnehmen", for: .normal)
    button.setTitleColor(CalendarSettings.Colors.darkRed, for: .normal)
    return button
}()

//MARK: - Init & View Loading
init(event: Event) {
    thisEvent = event
    super.init(nibName: nil, bundle: nil)
    setupDefaultValues()
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    applyDefaultValues()
    setupViews()
    confBounds()
}

//MARK: - Setup
func setupDefaultValues() {
    eventDescription = thisEvent.eventDescription
}

func applyDefaultValues() {
    descLabel.text = eventDescription
}

func setupViews() {
    view.addSubview(descLabel)
    view.addSubview(participateButton)

    let tabbarHeight = self.tabBarController?.tabBar.frame.height ?? 0
    descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    participateButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: tabbarHeight, paddingRight: 0, width: 0, height: 50) 
}

如果您要更改的是字体大小以使其适合标签,请尝试 adjustFontSizeToWidth,但如果是您要调整大小的标签,请尝试 sizeToFit()。

要使其自动调整大小,您必须给它一个 left/leading 和 right/trailing 约束,或者固定宽度

descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, rightview.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)