In Swift, I write code to do search list with TextField to users type keyword here, and when the users press ReturnKey, this app do search task, and show result in tableview(bellow TextField). I wrote:
func textFieldShouldReturn(textField: UITextField!) -> Bool {
var result = ArticleManager.GetListArticleSearch( textField.text , p: 1)
if( result.message == "success" ){
articles = result.articles
}
//textField.text = nil
textField.resignFirstResponder()
self.tblSearchResult?.reloadData()
return true
}
Seems to be OK.
But when press return key, because GetListArticleSearch
do in few seconds, so after few seconds the keyboard hide and tableview display result. In that time, my view look not nice, i can't scroll, can't do anything.
I want to when press return key, immediate hide keyboard, show a loading view, and when task done, show the list result in table view. (Not hide keyboard when task done.
The reason this is happening, as you said, is because GetListArticleSearch takes some time to finish and everything after it is waiting. You need to run this on different thread. Now it is running on main thread, thats why you cant move with table etc. You should run long taking tasks on background thread and when its finished update UI. Something like this:
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()//hidekeyboard
//you can add activity indicator
//run thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){
var result = ArticleManager.GetListArticleSearch( textField.text , p: 1)
if( result.message == "success" ){
articles = result.articles
}
//ui can be updated only from main thread
dispatch_async(dispatch_get_main_queue()){
self.tblSearchResult?.reloadData()
//stop activity indicator everything is done
}
}
return true
}
Here's a tutorial for GCD http://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1