我正在尝试使用 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])
}
如果我走了viewLeft
,并viewTop
因为它会跑好toItem:
是零在NSLayoutConstraint
。但我认为这个问题与toItem:
我尝试使用的问题有关self.view
,mainWindow
但它一直在抛出错误。
我已经看过很多关于如何做到这一点的例子,据我所知,我几乎是在复制它们,但它们都不是 Swift 4,所以我想知道 Swift 4 中是否有什么变化。
任何帮助都会很棒!谢谢你。
错误信息:
libc++abi.dylib:以未捕获的 NSException 类型异常(lldb)终止
我尝试使用 self.view 而不是主窗口和不同风格的布局约束。试试这个杰森布雷迪。
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句