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

7

我使用布局锚点编程方式创建了一个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

我该如何实现这种层次结构?
1个回答

12

你的操作是正确的,只是你没有提供足够的限制条件。我在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中运行的截图:

显示在Playground中运行的代码


1
是的,经过更多的测试,我也意识到了这一点。感谢您清晰的解释 :) - halapgos1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接