2015-04-01 85 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];