UISearchController change 'Cancel' button

2020-06-18 02:55发布

How we can change the title of cancel button in search controller?

enter image description here

11条回答
别忘想泡老子
2楼-- · 2020-06-18 03:30

You also need to have the searchBar setShowsCancelButton before the procedure.

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [theSearchBar setShowsCancelButton:YES animated:NO];
    for (UIView *subView in theSearchBar.subviews){
        if([subView isKindOfClass:[UIButton class]]){
            [(UIButton*)subView setTitle:@"Done" forState:UIControlStateNormal];
        }
    }
}

Note also use UIButton to avoid problems with Apple!

查看更多
对你真心纯属浪费
3楼-- · 2020-06-18 03:33

Worth noting, that the preferred method for changing the Cancel button title is now via appearances (got the idea from an another question: https://stackoverflow.com/a/34522163/511878):

[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"Annuler"];
查看更多
做自己的国王
4楼-- · 2020-06-18 03:34
  class ViewController: UIViewController,UISearchResultsUpdating {
        func updateSearchResults(for searchController: UISearchController) {
            //write your code here
        }
        @IBOutlet weak var navItem: UINavigationItem!
        let searchController = UISearchController(searchResultsController: nil)
        override func viewDidLoad() {
            super.viewDidLoad()
            searchController.obscuresBackgroundDuringPresentation = false
            searchController.definesPresentationContext = true
            searchController.searchResultsUpdater = self
            if #available(iOS 11.0, *){
                navigationItem.searchController = searchController
                UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "new title"
            }
            // Do any additional setup after loading the view.
        }
    }
查看更多
劫难
5楼-- · 2020-06-18 03:36

The solution provided above could change with new iOS releases. Here is a better approach:

[searchBar setValue:@"customString" forKey:@"_cancelButtonText"];
查看更多
贼婆χ
6楼-- · 2020-06-18 03:39

The Swift equivalent of Burhanuddin Sunelwala answer did the trick for me!

self.searchBar.setValue("custom string", forKey: "cancelButtonText")

Thanks to Burhanuddin Sunelwala for putting me in the right direction!

查看更多
趁早两清
7楼-- · 2020-06-18 03:41
for (UIView *subView in SearchBar.subviews) {
    if ([subView isKindOfClass:[UIButton class]]) {
        UIButton *cancelButton = (UIButton*)subView;

        [cancelButton setTitle:@"TitleString" forState:UIControlStateNormal];
}
查看更多
登录 后发表回答