2016-12-09 70 views
2

我發現的大多數示例都在Objective - C中,這對我來說很難理解,有人可以在Swift中提供有關此問題的示例。 Here是一個解決方案,但它在Objective CUISearchBar在用戶停止輸入時檢測到

+0

提出更明確,從而使他人能夠理解!你可以分享你提到的目標c的鏈接鏈接! – Lion

+0

好吧,我會編輯我的問題。 – user2273146

+0

您是否嘗試過searchBarTextDidEndEditing和searchBarShouldEndEditing? –

回答

1

你必須使用UISearchBarDelegate檢查一下:

func searchBarTextDidEndEditing(searchBar: UISearchBar) { 
    //DO what you want 
} 

記住補充:

searchBar.delegate = self 

而且他的親戚協議:

UISearchBarDelegate 

https://developer.apple.com/reference/uikit/uisearchbardelegate

該委託:當鍵盤消失searchBarTextDidEndEditing被調用,使代碼添加到您的凸出:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    self.view.endEditing(true) 
} 
+0

func searchBarTextDidEndEditing(searchBar:UISearchBar)print(「Type End」); } 最初我做了同樣的事情,但在類型結束後,該值不會打印在控制檯中,因此我認爲這不起作用。 – user2273146

+2

您必須添加:searchBar.delegate = self –

+0

覆蓋func viewDidLoad(){ super.viewDidLoad() //在加載視圖後,通常從一個筆尖執行任何其他設置。 /*設置代表*/ tableView.delegate =自 tableView.dataSource =自 searchBar.delegate =自 } 是的,我有提到,已經。 – user2273146

0

斯威夫特版本的鏈接:

var searchDelayer: Timer! 

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
    searchDelayer.invalidate(), searchDelayer = nil 
    if true { 
     searchDelayer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.doDelayedSearch), userInfo: searchText, repeats: false) 
    } 
} 

func doDelayedSearch(_ t: Timer) { 
    assert(t == searchDelayer) 
    self.request(searchDelayer.userInfo!) 
    searchDelayer = nil 
} 




var priorSearchText = "" 

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
     NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.request), object: priorSearchText) 
     priorSearchText = searchText 
    } 
    if true { 
     self.performSelector(#selector(self.request), withObject: searchText, afterDelay: 1.5) 
    } 
3
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { 
    print("after every text gets changed") 
    timer.invalidate() 
    timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(ViewController.output), userInfo: searchText, repeats: false) 
} 

func output(){ 
    print("hello") 
    if timer.userInfo != nil { 
     print(timer.userInfo) 
    } 
    timer.invalidate() 
} 
+0

這就是我解決我的問題的方法......謝謝大家的好評:) – user2273146