6

我以UIView编程方式使用layout anchors. 现在我想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

我怎样才能实现这种类型的层次结构?

4

1 回答 1

10

你做得对,你只是没有提供足够的约束。我在 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 的代码

于 2018-02-24T22:42:19.427 回答