以编程方式添加约束会导致崩溃

Adding constraints programmatically makes crash

我想在从底部新 table 视图滑动时以编程方式添加一些约束,但到目前为止我无法理解我做错了什么。在我的 super view 中,我有 map view 必须更改 bottom constraint 以便在单击按钮时为新的 tableView 创建 space。

基本上,对于我的 table 视图,我需要 4 个约束:

我总是崩溃:

Impossible to set up layout with view hierarchy unprepared for constraint.

基于以下设置约束:

这是一个代码:

@IBAction func test(_ sender: UIButton) {
        let tableView = UITableView()
        tableView.backgroundColor = UIColor.red
        tableView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tableView)

        let topConstraint = NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self.mapView, attribute: .bottom, multiplier: 1, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: self.tabBarController?.tabBar, attribute: .top, multiplier: 1, constant: 0)
        let leadingConstraint = NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)

        view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
//        tableView.addConstraint(NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self.mapView, attribute: .bottom, multiplier: 1, constant: 0))
//        tableView.addConstraint(NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: self.tabBarController?.tabBar, attribute: .top, multiplier: 1, constant: 0))
//        tableView.addConstraint(NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0))
//        tableView.addConstraint(NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0))

        self.view.layoutIfNeeded()
        UIView.animate(withDuration: 0.5, animations: {
            self.mapBottomConstaint.constant = 200
            self.centerButtonBottomConstaint.constant = 208
            self.view.layoutIfNeeded()
        })
    }

您正在尝试为视图层次结构之外的视图设置约束。自动布局系统提供布局指南,帮助您将视图与导航栏和标签栏对齐。

在底部约束中,将 self.tabBarController?.tabBar 替换为 bottomLayoutGuide

作为旁注,新的布局语法(在 iOS 9+ 上可用)使得在没有第三方库的情况下创建编程约束变得更加容易:

let topConstraint = tableView.topAnchor.constraint(equalTo: mapView.bottomAnchor)
let bottomConstraint = tableView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
let leadingConstraint = tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
let trailingConstraint = tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)

有关创建编程约束的更多信息here