Use UIRefreshControl for UIWebView

前端 未结 8 768
花落未央
花落未央 2021-02-01 08:24

I saw the UIRefreshControl in iOS 6 and my question is if it is possible to refresh a WebView by pulling it down and than let it pop up like in mail? Code I used rabih is the We

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 09:15

    My answer is based on @Zaid Pathan answer but updated for Swift 4.

    class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
    
    var refreshController:UIRefreshControl!
    var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    //Your webView initializing
    
        webView.scrollView.bounces = true //DONT FORGET IT!!!
    
        refreshController = UIRefreshControl()
    
        refreshController.bounds = CGRect(x: 0, y: 50, width: refreshController.bounds.size.width, height: refreshController.bounds.size.height)
        refreshController.addTarget(self, action: #selector(self.refreshWebView(refresh:)) , for: UIControlEvents.valueChanged)
        refreshController.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        webView.scrollView.addSubview(refreshController)
    }
    
    @objc func refreshWebView(refresh:UIRefreshControl){
        webView.reload()
    }
    

    Finally, don't forget to stop reloading:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if refreshController.isRefreshing{
            refreshController.endRefreshing()
        }
    }
    

提交回复
热议问题