2015-04-01 65 views
0

所以我有UISearchController,它顯示欄,我可以輸入文本但它不會觸發委託方法。這裏是我的代碼:UISearchController不會觸發委託方法和搜索欄委託方法

@IBAction func searchTapped(AnyObject) { 

    NSLog("search...") 

    let cancelButton = UIBarButtonItem(image: UIImage(named: "delete_sign-50"), landscapeImagePhone: nil, style: .Plain, target: self, action: "cancelTapped:") 

    var searchController = UISearchController(searchResultsController: nil) 
    searchController.dimsBackgroundDuringPresentation = false 
    searchController.searchBar.placeholder = "enter the text to search" 
    searchController.searchResultsUpdater = self; 
    searchController.hidesNavigationBarDuringPresentation = false 
    searchController.delegate = self 
    searchController.searchBar.delegate = self 

    self.definesPresentationContext = true; 


    UIView.animateWithDuration(0.2, animations: {() -> Void in 

     self.navigationItem.rightBarButtonItems = nil 
     self.navigationItem.rightBarButtonItems = [cancelButton] 
     self.navigationItem.titleView = searchController.searchBar 
     searchController.searchBar.sizeToFit() 
     self.toolbar.hidden = false 
     self.tableView?.hidden = false 
    }) 

    //add first responser to search bar 
    searchController.searchBar.becomeFirstResponder() 

} 

func updateSearchResultsForSearchController(searchController: UISearchController) { 

    NSLog("1 %@", searchController.searchBar.text); 

} 

func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 
    NSLog("2 %@", text) 
    return true 
} 

當文本改變時,這些方法都不會被調用。

不僅如此,我還嘗試將searchController作爲變量添加到我的控制器中,並且在那種情況下它可以運行焦炭 - 當我點擊搜索欄時,它會離開屏幕。

+0

你有沒有確認UISearchController委託。 – sample 2015-04-01 18:54:18

回答

2
searchController.active = YES; 

這有幫助,不知道爲什麼它沒有提到任何地方。

0

對於IOS 9

-(void)viewDidLoad 
_searchController = [[UISearchController alloc] initWithSearchResultsController:self]; 
    self.navigationItem.titleView = _searchController.searchBar; 
    self.definesPresentationContext = YES; 
    _searchController.delegate = self; 
    _searchController.searchBar.delegate = self; 
    _searchController.searchBar.placeholder = NSLocalizedString(@"SEARCHTITLE", nil); 
    [_searchController.searchBar setShowsCancelButton: YES animated: NO];