我已经使用 layout anchors
以编程方式创建了一个 UIView
。现在我想在此 View 中添加一个 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
显示的。这是当前的 View 层次结构:
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 中运行:
关于ios - 以编程方式使用布局 anchor 创建 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968233/