Search code examples
xcodeswiftuiwebviewtoolbaruitoolbar

(Xcode / Swift) How to hide toolbar when scrolling down UIWebView?


I have a UIWebView in my ViewController and a navigation controller embedded in my ViewController. In my navigation controller, I selected "Show Toolbar" and "Hide Bars on Swipe" but the Toolbar doesn't hide. It only works when "Show Navigation Bar" is selected with the Toolbar.

Is there anyway to have the Toolbar hide on swipe when scrolling down the UIWebView?

Thank you in advanced.


Solution

  • You can use UIScrollViewDelegate for that.

    Here is example code for hide navigation bar and tool bar with scroll:

    import UIKit
    
    class ViewController: UIViewController, UIScrollViewDelegate {
    
        @IBOutlet weak var toolBar: UIToolbar!
        @IBOutlet weak var webV: UIWebView!
        var lastOffsetY :CGFloat = 0
        override func viewDidLoad() {
            super.viewDidLoad()
    
            webV.scrollView.delegate = self
            let url = "http://apple.com"
            let requestURL = NSURL(string:url)
            let request = NSURLRequest(URL: requestURL!)
            webV.loadRequest(request)
        }
    
        //Delegate Methods
        func scrollViewWillBeginDragging(scrollView: UIScrollView){
            lastOffsetY = scrollView.contentOffset.y
        }
    
        func scrollViewWillBeginDecelerating(scrollView: UIScrollView){
    
            let hide = scrollView.contentOffset.y > self.lastOffsetY
            self.navigationController?.setNavigationBarHidden(hide, animated: true)
            toolBar.hidden = hide
        }
    }