2015-04-04 39 views
3

我有UIViewController,它採用了UISearchBarDelegate。並將其代理設置爲self:resultSearchController.searchBar.delegate = self。它工作正常,我searchBarCancelButtonClicked方法%Swift:searchBar - 如何更改「取消」按鈕標題

func searchBarCancelButtonClicked(searchBar: UISearchBar) { 
     println("Сancel button tapped") 
    } 

測試它我看到「Сancel按鈕竊聽」控制檯。但我想改變「取消」按鈕標題,我不知道如何。我試過:

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {  
     var barButton = UIBarButtonItem(title: "Button Title", style: UIBarButtonItemStyle.Done, target: self, action: "here") 
     self.resultSearchController.searchBar.showsCancelButton = false 
     self.resultSearchController.navigationItem.rightBarButtonItem = barButton 
    } 

但它不起作用。請問你能幫幫我嗎?

回答

2
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) { 
    self.searchDisplayController?.searchBar.showsCancelButton = true 
    var cancelButton: UIButton 
    var topView: UIView = self.searchDisplayController?.searchBar.subviews[0] as UIView 
    for subView in topView.subviews { 
     if subView.isKindOfClass(NSClassFromString("UINavigationButton")) { 
      cancelButton = subView as UIButton 
      cancelButton.setTitle("Vazgeç", forState: UIControlState.Normal) 
     } 
    } 
} 
+0

我不使用UISearchDisplayController它已棄用。我使用UISearchController。所以這段代碼不能幫助我。 – user3742622 2015-04-04 16:59:39

0

所有你需要顯示導航控制器自定義搜索欄按鈕像

在viewDidLoad中()

首先

self.searchDisplayController?.displaysSearchBarInNavigationBar =真

和代表方法

func searchBarTextDidBeginEditing(searchBar: UISearchBar) { 

    var barButton = UIBarButtonItem(title: "Button Title", style: UIBarButtonItemStyle.Done, target: self, action: "here") 
    self.searchDisplayController?.navigationItem.rightBarButtonItem = barButton 
} 
+0

我試過你的代碼。沒有任何變化 - 我看到搜索欄中顯示「取消」,抱歉,也許我錯過了這一點...請給我更多的信息。 – user3742622 2015-04-04 15:02:02

+0

請,我已經在這幾個小時內打破了我的大腦......我不使用UISearchDisplayController它已棄用。我使用UISearchController。 – user3742622 2015-04-04 20:40:33

0

我用UISearchBar對象中的UIButton指針解決了這個問題。我有我的項目的Objective-C代碼,但你可以看到邏輯。

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { 

    [searchBar setShowsCancelButton:YES animated:YES]; 

    for (UIView *ob in ((UIView*)searchBar.subviews[0]).subviews) { 
     if ([ob isKindOfClass:[UIButton class]]) { 
      UIButton *btn = (UIButton*)ob; 
      [btn setTitle:@"İptal" forState:UIControlStateNormal]; 
     } 
    } 
    return YES; 
}