HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 以编程方式使用布局锚创建子视图大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经使用布局锚点以编程方式创建了一个UIView.现在我想在这个视图中添加一个UILabel.到目前为止,这是我的代码

let centerView = UIView()
centerView.translatesAutoresizingMaskIntoConsTraints = false
centerView.BACkgroundColor = UIColor.white
view.addSubview(centerView)
centerView.leftAnchor.consTraint(equalTo: view.leftAnchor,consTraint: 20).isActive = true
centerView.rightAnchor.consTraint(equalTo: view.rightAnchor,consTraint: -20).isActive = true

let label = UILabel()
label.translatesAutoresizingMaskIntoConsTraints = false
label.text = "TesTing" 
label.textColor = UIColor.black
centerView.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 = false
centerView.BACkgroundColor = UIColor.white
view.addSubview(centerView)
centerView.leftAnchor.consTraint(equalTo: view.leftAnchor,constant: 20).isActive = true
centerView.rightAnchor.consTraint(equalTo: view.rightAnchor,constant: -20).isActive = true
centerView.topAnchor.consTraint(equalTo: view.topAnchor,constant: 20).isActive = true
centerView.bottomAnchor.consTraint(equalTo: view.bottomAnchor,constant: -20).isActive = true

let label = UILabel()
label.translatesAutoresizingMaskIntoConsTraints = false
label.text = "TesTing"
label.textColor = UIColor.black
label.BACkgroundColor = UIColor.yellow
centerView.addSubview(label)
label.leftAnchor.consTraint(equalTo: centerView.leftAnchor).isActive = true
label.topAnchor.consTraint(equalTo: centerView.topAnchor).isActive = true

view.layoutIfNeeded()

这是在游乐场运行:

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

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。