在 UIStackView 中更新标签的文本并同时保持文本居中?

Update a label's text in a UIStackView and while keeping the text centered?

当我在堆栈视图中放置带有居中文本的标签,然后更新文本时,它不再居中显示。

import PlaygroundSupport
import UIKit

let stackView = UIStackView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 20)))

let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 20)))
label.text = "Hello"
label.textAlignment = .center

stackView.addArrangedSubview(label)

label.text = "World"

PlaygroundPage.current.liveView = stackView

预期的结果是“世界”居中。但是,它看起来是左对齐的。调用 layoutSubviews() 没有帮助。

如果没有 auto-layout,堆栈视图将无法正常播放 - 特别是在 Playgrounds 中。

这样试试:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()

        view.backgroundColor = .white

        let stackView = UIStackView()
        
        let label = UILabel()
        label.text = "Hello"
        label.textAlignment = .center

        // so we can see the frame
        label.backgroundColor = .green
        
        stackView.addArrangedSubview(label)
        
        label.text = "World"

        view.addSubview(stackView)
        
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            stackView.widthAnchor.constraint(equalToConstant: 100.0),
            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0),
        ])
        
        self.view = view
    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()