I'm attempting to add a UIView with NSLayoutConstraints but I keep getting an uncaught exception of type NSException error. The main reason I'm doing it with code instead of in the storyboard is I want it to be above the Navigation bar on the UITableViewController.
Here is the code I currently have.
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])
}
If I take out the viewLeft
and viewTop
it will run okay since the toItem:
is nil in NSLayoutConstraint
. But I think the problem has something to do with that toItem:
I've tried using self.view
and mainWindow
but it keeps throwing the error.
I've seen lots of examples of how to do this and I'm pretty much copying them as far as I can tell, but none of them were Swift 4 so I'm wondering if something changed in Swift 4.
Any help would be great! Thank you.
Error Message:
libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
I tried with self.view instead of main window and with the different style of layout constraints. Just try this 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
}