更新 UIStackView 中标签的文本并同时保持文本居中?
当我在堆栈视图中放置带有居中文本的标签,然后更新文本时,它不再显示居中。
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()没有帮助。
When I place a label with centered text in a stack view, then update the text, it no longer appears 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
The expected outcome is that "World" is centered. However, it appears leftaligned. Calling layoutSubviews() did not help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有自动布局,堆栈视图就不能很好地发挥作用 - 特别是在 Playgrounds 中。
试试这样:
Stack views don't play well without auto-layout - particularly in Playgrounds.
Try it like this: