2017-04-10 72 views
0

我有UITextField用於輸入搜索字符串和UITableView的結果。 我想要的是運行搜索功能,當用戶輸入超過3個字母,並且它自從最後一個符號添加到UITextView以來至少過0.5秒。在swift iOS應用程序中的延遲搜索

我發現(Detect when user stopped/paused typing in Swift)功能,我把它添加到我的ViewController是具有類SearchVC和方法server_search

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    NSObject.cancelPreviousPerformRequests(
     withTarget: self, 
     selector: #selector(SearchVC.server_search), 
     object: textField) 
    self.perform(
     #selector(SearchVC.server_search), 
     with: textField, 
     afterDelay: 0.5) 
    return true 
} 

但沒有任何反應。

+1

任何您不使用計時器的原因? –

回答

1

您可以用Timer實現這個...

var timer: Timer? 

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

    timer?.invalidate() // Cancel any previous timer 

    // If the textField contains at least 3 characters… 
    let currentText = textField.text ?? "" 
    if (currentText as NSString).replacingCharacters(in: range, with: string).characters.count >= 3 { 

     // …schedule a timer for 0.5 seconds 
     timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(performSearch()), userInfo: nil, repeats: false) 
    } 

    return true 
} 

func performSearch() { 

} 

而且不要忘記設置視圖控制器是你UITextFielddelegate

+0

使用Swift 3你可以在定時器上使用一個完成塊。這似乎使事情更容易使用和閱讀。 :) – LinusGeffarth

+0

感謝您「不要忘記將視圖控制器設置爲您的UITextField委託」 - 這是主要問題! – moonvader

1

定時器的使用有一定的優勢。隨着你的實現,你會取消 所有的執行你的對象,這是可能失控的事情。

一個計時器,而是讓你細粒控制它。請參閱以下實施:

var searchTimer: Timer? 
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    // Invalidate remove the previous timer, since it's optional if the previous timer is already cancelled or nil, it won't affect execution 
    searchTimer?.invalidate() 
    searchTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { (timer) in 
     //do Something crazy 
     self.server_search() 
    }) 
    return true 
} 
+1

謝謝你的回答 - 它似乎很好,但我選擇了Ashley Mills的答案,因爲它有字符串長度檢查,並且不需要iOS 10 – moonvader