我特别喜欢 AutoLayout,因为我可以使页眉的高度动态化。
这是我在控制器中使用 AutoLayout 的代码,其中引用“headerView”到标题视图和“webView”到 webView。
// Function called in ViewDidLoad:
func addHeaderToWebView(){
// We load the headerView from a Nib
headerView = NSBundle.mainBundle().loadNibNamed(WebViewHeader.nibName, owner: self, options: nil).first as! WebViewHeader
headerView.translatesAutoresizingMaskIntoConstraints = false
webView.scrollView.addSubview(headerView)
// the constraints
let topConstraint = NSLayoutConstraint(item: headerView, attribute: .Bottom, relatedBy: .Equal, toItem: webView.scrollView, attribute: .Top, multiplier: 1, constant: 0)
let leftConstraint = NSLayoutConstraint(item: headerView, attribute: .Leading, relatedBy: .Equal, toItem: webView, attribute: .Leading, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: headerView, attribute: .Trailing, relatedBy: .Equal, toItem: webView, attribute: .Trailing, multiplier: 1, constant: 0)
// we add the constraints
webView.scrollView.addConstraints([topConstraint])
webView.addConstraints([leftConstraint, rightConstraint])
}
// Function called in viewWillLayoutSubviews: to update the scrollview of the webView content inset
func updateWebViewScrollViewContentInset(){
webView.scrollView.contentInset = UIEdgeInsetsMake(headerView.frame.height, 0, 0, 0)
}