我试图通过添加可视格式的约束来在我的UITableViewController上添加简单的红色视图。这是我的代码(在viewDidLoad中调用):
private func setupMenuBar() {
let myView = UIView()
myView.backgroundColor = UIColor.red
view.addSubview(myView)
view.addConstraintsWithFormat(format: "H:|[v0]|", views: myView)
view.addConstraintsWithFormat(format: "V:|[v0]|", views: myView)
这是我对UIView类的扩展:
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
在我的另一个空testViewController上工作正常:没有任何子视图的UIViewController。 正如您在图片中看到的,这里没有任何红色视图: App hierarchy
在函数结束时我有零帧: Console