Search code examples
iosuitableviewswiftreloaddatafirst-responder

how to wait until firstResponder of text label is false in swift


I'm new to swift. My app uses photos people upload to the web and showing the photos in a table view. It is reloading whenever some user uploads a new photo. I have a UITextField that when you press it the keyboard goes up. My problem is that it goes down whenever reloadView is happening (when a new photo arrives) What i'm trying to do is to check if the UITextField is first recogniser and if so I want to wait with the reload until it not first recogniser.

func refreshView()
{
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            while (self.dataSource.writeSomethingTextLabel.isFirstResponder()) {
                //need to wait somehow for notification that it is not first responder anymore
            }
            self.tableView.reloadData()
        }
}

So with this code the keyboard is not going down of course but the wile loop runs and everything is stuck. my question is how can I wait until the user finishes using the text label (first responder is false). thanks


Solution

  • You can conditionally reload tableView on two places: when new data arrives and when textField ends editing:

    @class YourViewController: UIViewController, UITextFieldDelegate {
    
        var needsToReloadTableView = false;
    
        func reloadTableViewIfNeeded() {
            if needsToReloadTableView {
                self.tableView.reloadData()
                needsToReloadTableView = false
            }
        }
    
        func gotNewData() {
            needsToReloadTableView = true
    
            if !self.textField.isFirstResponder {
                reloadTableViewIfNeeded()
            }
        }
    
        func textFieldDidEndEditing(textField:UITextField) {
            reloadTableViewIfNeeded()
        }
    
    }