当我在堆栈视图中放置带有居中文本的标签,然后更新文本时,它不再显示为居中。
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((没有帮助。
如果没有自动布局,堆栈视图就不能很好地播放,尤其是在操场上。
这样试试:
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()