gpt4 book ai didi

ios - 在 Stack View 的 UIView 中居中 UILabel

转载 作者:行者123 更新时间:2023-11-28 20:54:57 25 4
gpt4 key购买 nike

我在 Storyboard 中安排了一个水平堆栈 View 。至于堆栈 View 的 View ,它是通过编程完成的,因为堆栈 View 内的 View 数量是动态的。我已将堆栈 View 设置为“平均填充”。

对于里面的 View ,会有一个UIlabel。我遇到的问题是我无法将 UILabel 置于将添加到堆栈 View 中的 UIView 内。

这是我的代码:

    let main1 = UIView()
main1.backgroundColor = UIColor.red
stackView.addArrangedSubview(main1)

let text1 = UILabel()
text1.text = "Lvl 1"
text1.textColor = .blue
text1.textAlignment = .center
text1.backgroundColor = .yellow
text1.sizeToFit()
main1.addSubview(text1)


let label2 = UIView()
label2.backgroundColor = UIColor.blue
stackView.addArrangedSubview(label2)

对于这个例子,我只添加了 2 个 View ,标签添加到第一个 View 。那么,我如何才能将每个 UIView 中的 UILabel 居中呢?

最佳答案

您可以使用自动布局来实现这一点。检查下面的代码:

...

main1.addSubview(text1)

text1.translatesAutoresizingMaskIntoConstraints = false
text1.centerXAnchor.constraint(equalTo: main1.centerXAnchor).isActive = true
text1.centerYAnchor.constraint(equalTo: main1.centerYAnchor).isActive = true

关于ios - 在 Stack View 的 UIView 中居中 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com