如何更改UISearchBar + iPhone中显示的取消按钮的默认文本

Pra*_*ypa 26 iphone uisearchbar ios

我正在开发一个应用程序,我想在SearchBar中更改搜索字符串的文本.我想更改SearchBar旁边显示的取消按钮的文本.在搜索栏中输入任何字符串之前,我们将获取搜索字符串作为默认字符串.我想更改该字符串的文本,当我们点击该搜索栏时,我们会在搜索栏旁边找到一个取消按钮,我想更改该取消按钮的文本.

Yar*_*sim 50

使用外观代理:

id barButtonAppearanceInSearchBar = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];

[barButtonAppearanceInSearchBar setBackgroundImage:grayBackgroundImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[barButtonAppearanceInSearchBar setTitleTextAttributes:@{
                                      NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:20],
                                 NSForegroundColorAttributeName : [UIColor blackColor]
     } forState:UIControlStateNormal];
[barButtonAppearanceInSearchBar setTitle:@"X"];
Run Code Online (Sandbox Code Playgroud)

  • setTitle:从今天起在iOS7上为Xcode 5上的这段代码失败了 (11认同)

Dav*_*one 35

您还需要在该过程之前使用"searchBar setShowsCancelButton".

- (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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意:使用UIButton可以避免Apple出现问题!

  • 不要再使用这个hack,使用UIAppearance.在此处查看更多信息http://stackoverflow.com/a/14509280/296649 (3认同)
  • 这在iOS6中运行良好,但你必须在iOS7中更深入一层.更改行:for(在SearchBar.subviews中的UIView*subView){to for([[personNameField.subviews objectAtIndex:0] subviews]中的[UIView*subView]){另请注意,您可以通过放置来轻松检查您是否在iOS7上NSString*version = [[UIDevice currentDevice] systemVersion]; if([version hasPrefix:@"7."]){ (3认同)
  • 绝对正确 - [UIButton类]是更好的语法! (2认同)

SGI*_*SGI 23

适用于iOS 7的解决方案.所有这些都归功于Jesper Nielsen先生 - 他编写了代码.

-(void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
    UIButton *cancelButton;
    UIView *topView = theSearchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
    }
    if (cancelButton) {
        [cancelButton setTitle:@"YourTitle" forState:UIControlStateNormal];
    }

}
Run Code Online (Sandbox Code Playgroud)