您做得很正确,只是没有提供足够的约束。我在Swift游乐场中尝试了您的代码,并添加了一些额外的约束,这表明标签是相对于
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()
下面是在操场上跑步: