Swift - Disable refreshControl while searching

2020-07-09 03:42发布

问题:

During the search I want to disable the pull to refresh mechanism. So I disabled the refresh control and removed it. But when pull down to refresh the beginRefresh method is called and the cells keep being down for 2 seconds like there is a refresh.

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    resultSearchController.searchBar.selectedScopeButtonIndex = 0
    refreshControl!.enabled = false
    refreshControl?.removeFromSuperview()
    return true
}

回答1:

When search then check if refreshControl has superView and Remove from superView After search End Add it again, the condition will look like :

  if self.refreshControl.isDescendant(of: self.tblView) {
      self.refreshControl.removeFromSuperview() 
  }


回答2:

Use these two functions if you want to create or delete refresh controls in the top of UITableView.

func createRefreshControl() {
    // Create RefreshControl and add to tableView
    self.refreshControl = UIRefreshControl()
    self.refreshControl!.attributedTitle = NSAttributedString(string: " ↓ Refresh ↓ ")
    self.refreshControl!.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
}

func deleteRefreshControl() {
    // delete RefreshControl
    self.refreshControl = nil
}


回答3:

Try with this code, it worked for me:

var refresh : UIRefreshControl!

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    print("START TABBAR")
    if #available(iOS 10.0, *) {
        if let refresh = self.tableView.refreshControl {
            if refresh.isDescendant(of: self.tableView) {
                self.tableView.refreshControl?.removeFromSuperview()
            }
        }
    } else {
        for subview in self.tableView.subviews {
            if let refresh = subview as? UIRefreshControl {
                refresh.removeFromSuperview()
            }
        }
    }
}


func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    print("FINISH SEARCH")
    self.refresh = UIRefreshControl()
    self.refresh.attributedTitle = NSAttributedString(string: "Update data")
    self.refresh.addTarget(self, action: #selector(updateFunction), for: .valueChanged)
    if #available(iOS 10.0, *) {
        self.tableView.refreshControl = self.refresh
    } else {
        self.tableView.addSubview(self.refresh)
    }
}

@objc func updateFunction() {
    //Your function to update the tableView
}

You will need to implement the UISearchBarDelegate in order to call those functions.

It also works for iOS 9

Best regards