尽管这可能与原始问题不完全相关,但在尝试自定义 UISearchBar 中的取消按钮的更大意义上,该解决方案仍然适用。认为这将帮助其他陷入这种情况的人。
我的情况是更改取消按钮的标题,但有一个转折,其中我不想默认显示取消按钮,但只想在用户进入搜索模式时显示它(通过在搜索文本字段内单击)。此时,我希望取消按钮带有“完成”的标题(“取消”给我的屏幕赋予了不同的含义,因此进行了自定义)。
不过,这就是我所做的(结合了 caelavel 和 Arenim 的解决方案):
使用以下两种方法将 UISearchBar 子类化为 MyUISearchBar:
-(void) setCloseButtonTitle: (NSString *) title forState: (UIControlState)state
{
[self setTitle: title forState: state forView:self];
}
-(void) setTitle: (NSString *) title forState: (UIControlState)state forView: (UIView *)view
{
UIButton *cancelButton = nil;
for(UIView *subView in view.subviews){
if([subView isKindOfClass:UIButton.class])
{
cancelButton = (UIButton*)subView;
}
else
{
[self setTitle:title forState:state forView:subView];
}
}
if (cancelButton)
[cancelButton setTitle:title forState:state];
}
在使用此 Searchbar 的视图控制器中,以下代码负责显示取消按钮并自定义其标题:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
MyUISearchBar *sBar = (MyUISearchBar *)searchBar;
[sBar setShowsCancelButton:YES];
[sBar setCloseButtonTitle:@"Done" forState:UIControlStateNormal];
}
奇怪的是,当退出搜索模式时,我不需要做任何事情来隐藏取消按钮,因为默认情况下它是隐藏的。