Search code examples
iosswiftrefresh

How do I refresh when touch drag is finished on Swift?


I have a problem with the refresh part. Currently, the function to refresh is OK.

But I want to refresh when the user has finished touching the iphone.

var refController:UIRefreshControl = UIRefreshControl()
override func viewDidLoad() {
    super.viewDidLoad()
    refController.bounds = CGRect.init(x: 0.0, y: 40.0, width: refController.bounds.size.width, height: refController.bounds.size.height)
    refController.addTarget(self, action: #selector(self.webviewRefresh(refresh:)), for: .valueChanged)
    refController.attributedTitle = NSAttributedString(string: "refreshing")
    WKWebView.scrollView.addSubview(refController)
    if contentController.userScripts.count > 0 {
        contentController.removeAllUserScripts()
    }
...
}
@objc func webviewRefresh(refresh:UIRefreshControl){
    refController.endRefreshing()
    WKWebView.reload()
}

Currently, Even if user haven't finished touch at this time, when the screen is lowered to a certain height, a refresh is performed on the screen.

But I want to run a refresh when the user has finished touching the screen.


Solution

  • You have to call refresh method in scrollViewDidEndDecelerating delegate method of UIScrollViewDelegate. So import UIScrollViewDelegate in your ViewController Like,

    extension YourViewController: UIScrollViewDelegate {
        func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            if self.refController.isRefreshing {
                self.webviewRefresh()
            }
        }
    }
    

    Then your webviewRefresh will be,

        @objc func webviewRefresh(){
            refController.endRefreshing()
            WKWebView.reload()
        }
    

    And yourviewDidLoad will be,

       override func viewDidLoad() {
            super.viewDidLoad()
            refController.bounds = CGRect.init(x: 0.0, y: 40.0, width: refController.bounds.size.width, height: refController.bounds.size.height)
            refController.attributedTitle = NSAttributedString(string: "refreshing")
            WKWebView.scrollView.addSubview(refController)
            WKWebView.scrollView.delegate = self
            if contentController.userScripts.count > 0 {
                contentController.removeAllUserScripts()
            }
        }