Adding a header view to a UIWebView similar to Safari and Articles

前端 未结 7 1860
耶瑟儿~
耶瑟儿~ 2020-12-07 19:17

I\'d like to add a header view to an UIWebView similar to the address/search bar in MobileSafari and the excellent Articles.app by Sophia Teutschler. More preci

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 19:48

    I like AutoLayout specially because I can make the height of the header dynamic.

    This is my code using AutoLayout in a controller with a reference 'headerView' to the header view and a 'webView' to the 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)
    }
    

提交回复
热议问题