使用 Swift 4 以编程方式将 UIView 添加到具有 NSLayoutConstraints 的 UITableViewController

Adding a UIView to a UITableViewController with NSLayoutConstraints programmatically with Swift 4

我正在尝试添加带有 NSLayoutConstraints 的 UIView,但我一直收到 NSException 类型的未捕获异常错误。我用代码而不是故事板来做这件事的主要原因是我希望它位于 UITableViewController 的导航栏上方。

这是我目前拥有的代码。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let mainWindow: UIWindow = UIApplication.shared.keyWindow!

    let newView = UIView()
    newView.backgroundColor = UIColor.darkAqua
    newView.translatesAutoresizingMaskIntoConstraints = false

    mainWindow.addSubview(newView)

    let viewHeight = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewWidth = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    let viewLeft = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 40)
    let viewTop = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: mainWindow, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

    newView.addConstraints([viewHeight, viewWidth, viewLeft, viewTop])
}

如果我取出 viewLeftviewTop 它将 运行 没问题,因为 toItem:NSLayoutConstraint 中为零。但我认为问题与 toItem: 有关,我尝试使用 self.viewmainWindow 但它一直在抛出错误。

我看过很多关于如何执行此操作的示例,据我所知,我几乎是在复制它们,但是 none 其中 Swift 4 所以我'我想知道 Swift 4.

中是否发生了某些变化

任何帮助都会很棒!谢谢。

错误信息:

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

我尝试使用 self.view 而不是 main window 和不同风格的布局约束。试试这个 Jason Brady。

override func viewDidLoad() {
    super.viewDidLoad()

    let newView = UIView()
    newView.backgroundColor = UIColor.red
    newView.translatesAutoresizingMaskIntoConstraints = false

    self.view.addSubview(newView)


    newView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 40).isActive = true
    newView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
    newView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}