方法1
遵守UISearchBarDelegate代理协议;
然后实现- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar这个代理方法;
在代理方法中,加入以下代码:
searchBar.showsCancelButton = YES;
for (id cencelButton in [searchBar.subviews[0] subviews])
{
if([cencelButton isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)cencelButton;
[btn setTitle:@"取消" forState:UIControlStateNormal];
}
}
其中,searchBar.showsCancelButton = YES是必须的,不然不能把英文的“cancel”改成中文的“取消”。
方法2
[searchBar setValue("取消", forKey: "_cancelButtonText")];
这种写法解决了上面那种写法在弹出取消按钮时不自然的问题。
iOS9以后可以这样写:
[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].title = @"取消";