ios – 以编程方式使用布局锚创建子视图

ios – 以编程方式使用布局锚创建子视图,第1张

概述我已经使用布局锚点以编程方式创建了一个UIView.现在我想在这个视图中添加一个UILabel.到目前为止,这是我的代码: let centerView = UIView()centerView.translatesAutoresizingMaskIntoConstraints = falsecenterView.backgroundColor = UIColor.whiteview.add 我已经使用布局锚点以编程方式创建了一个UIVIEw.现在我想在这个视图中添加一个UILabel.到目前为止,这是我的代码:

let centerVIEw = UIVIEw()centerVIEw.translatesautoresizingMaskIntoConstraints = falsecenterVIEw.backgroundcolor = UIcolor.whitevIEw.addSubvIEw(centerVIEw)centerVIEw.leftAnchor.constraint(equalTo: vIEw.leftAnchor,constraint: 20).isActive = truecenterVIEw.rightAnchor.constraint(equalTo: vIEw.rightAnchor,constraint: -20).isActive = truelet label = UILabel()label.translatesautoresizingMaskIntoConstraints = falselabel.text = "Testing" label.textcolor = UIcolor.blackcenterVIEw.addSubvIEw(label)label.leftAnchor.constraint(equalTo: centerVIEw.leftAnchor).isActive = true

我认为这个标签会在参考centerVIEw时显示,但它是在参考UIWindow时显示的.这是当前的视图层次结构:

UIWindow --> UIVIEw (centerVIEw) --> UILabel (label)

我需要在centerVIEw中添加多个标签,根据我的理解,这个链会变长,而我想要几个标签都在centerVIEw下面

UIWindow            |     UIVIEw (centerVIEw)     /      |      \  Label 1  Label 2  Label 3

我怎样才能实现这种层次结构?

解决方法 你正确地做了,你没有提供足够的约束.我在Swift Playground中尝试了您的代码并添加了一些额外的约束,它显示标签相对于centerVIEw按预期放置:

let vIEw = UIVIEw(frame: CGRect(x: 0,y: 0,wIDth: 300,height: 500))let centerVIEw = UIVIEw()centerVIEw.translatesautoresizingMaskIntoConstraints = falsecenterVIEw.backgroundcolor = UIcolor.whitevIEw.addSubvIEw(centerVIEw)centerVIEw.leftAnchor.constraint(equalTo: vIEw.leftAnchor,constant: 20).isActive = truecenterVIEw.rightAnchor.constraint(equalTo: vIEw.rightAnchor,constant: -20).isActive = truecenterVIEw.topAnchor.constraint(equalTo: vIEw.topAnchor,constant: 20).isActive = truecenterVIEw.bottomAnchor.constraint(equalTo: vIEw.bottomAnchor,constant: -20).isActive = truelet label = UILabel()label.translatesautoresizingMaskIntoConstraints = falselabel.text = "Testing"label.textcolor = UIcolor.blacklabel.backgroundcolor = UIcolor.yellowcenterVIEw.addSubvIEw(label)label.leftAnchor.constraint(equalTo: centerVIEw.leftAnchor).isActive = truelabel.topAnchor.constraint(equalTo: centerVIEw.topAnchor).isActive = truevIEw.layoutIfNeeded()

这是在游乐场运行:

总结

以上是内存溢出为你收集整理的ios – 以编程方式使用布局锚创建子视图全部内容,希望文章能够帮你解决ios – 以编程方式使用布局锚创建子视图所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1073409.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存