以下是在ViewController中初始化UIView并将其约束到ViewController的主视图后收到的错误消息。Unable to activate constraint with anchors because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.
如果你看我提供的图片,你会发现在故事板中,我可以在主视图中放置另一个UIView,然后我可以将其约束到主视图的边缘。这工作得很好,但我想知道如何在代码中做同样的事情。仅仅使用NSLayoutConstraint并将其固定到顶部、底部、前导和尾随似乎对我不起作用。任何关于这方面的见解都会很好。
let webView: WKWebView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: webView,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0).isActive = true
let url = NSURL (string: someURL);
let requestObj = NSURLRequest(url: url! as URL);
webView.load(requestObj as URLRequest);
}
最佳答案
在添加约束之前,您似乎忘记将webView
添加到view
:
view.addSubview(webView)
最终代码:
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
NSLayoutConstraint(item: webView,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1.0,
constant: 0.0).isActive = true
NSLayoutConstraint(item: webView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0.0).isActive = true
let url = NSURL (string: "");
let requestObj = NSURLRequest(url: url! as URL);
webView.load(requestObj as URLRequest);
关于ios - 为什么不能将在viewDidLoad方法中创建的 View 限制为ViewControllers View ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43219849/