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

Creating subviews using layout anchors programmatically

我使用 layout anchors 以编程方式创建了一个 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()

这里是 运行 在 Playground 中: