Search code examples
swiftxcodeuiscrollviewwkwebview

Swift - scrollViewDidScroll not working with WKWebView


I'm trying to add a shadow to my (custom) nav bar when a user scrolls using scrollViewDidScroll but it doesn't do anything. I have the same exact code on another view controller but it has a tableView instead of a WKWebView and it works fine.

I tried adding webView.scrollView.delegate = self but I just get an error.

My code:

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var navBar: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        addShadow()
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let navigationBar = navBar
        let offset = scrollView.contentOffset.y / 10
        if offset > 1.5 {
            navigationBar?.layer.shadowOpacity = 0.15
        } else {
            navigationBar?.layer.shadowOpacity = Float(((3 * offset) / 20)/1.5)
        }
    }

    func addShadow() {
        navBar.layer.shadowColor = UIColor.black.cgColor
        navBar.layer.shadowOffset = CGSize(width: 0, height: 2.0)
        navBar.layer.shadowRadius = 6.0
        navBar.layer.masksToBounds = false
    }
}

Solution

  • I tried adding webView.scrollView.delegate = self but I just get an error.

    You didn't share what the error was. I suspect though that you didn't declare your view controller as UIScrollViewDelegate conforming, which caused the compile time error when trying to set self as the scroll view delegate.

    Change your view controller declaration to this:

    class ViewController: UIViewController, UIScrollViewDelegate {