我使用布局锚点
编程方式创建了一个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
我该如何实现这种层次结构?