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:52

You should use the appearance proxy of the UISearchBar. You can find an example here - How to change the default text of Cancel Button which appears in the UISearchBar +iPhone

查看更多
家丑人穷心不美
3楼-- · 2020-06-18 03:52

swift version:

for view:UIView in (searchView?.subviews)!
{
        for subView:UIView in (view.subviews)
        {
            if ( subView is UIButton )
            {
                let cancelBut = subView as! UIButton

                //do stuff with cancelButton here
            }
        }
    }
查看更多
疯言疯语
4楼-- · 2020-06-18 03:53

You can change the "Cancel" Button in search bar using this-

for (UIView *view in searchBar.subviews)
{
    for (id subview in view.subviews)
    {
        if ( [subview isKindOfClass:[UIButton class]] )
        {
            [subview setEnabled:YES];
            UIButton *cancelButton = (UIButton*)subview;
            [cancelButton setTitle:@"hi" forState:UIControlStateNormal];


            NSLog(@"enableCancelButton");
            return;
        }
    }
}
查看更多
萌系小妹纸
5楼-- · 2020-06-18 03:53

Swift 4.2, 4.0+

A custom class that supports many customizations with the below results is added in the answer here.

enter image description here

查看更多
在下西门庆
6楼-- · 2020-06-18 03:54

swift 4 & 5

The best and simple way that worked for me is this snippet of code:

if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.setTitle("Annuler", for: .normal)
}

You can modify more properties like this:

if let cancelButton = searchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.setTitle(<your_string>, for: <UIControlState>)
    cancelButton.setTitleColor(<your_uicolor>, for: <UIControlState>)
    cancelButton.setAttributedTitle(<your_nsattributedstring>, for: <UIControlState>)
}

I hope this helps :)

查看更多
登录 后发表回答