2
//Set all cancel buttons in search bars to "Done"
id searchBarButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
if([[[UIDevice currentDevice] systemVersion] floatValue] < 7) {
    [searchBarButton setTitle:@"Done"];
} else {
    //Can't do anything here or i get EXC_BAD_ACCESS
}

viewDidLoad仅在 iOS 7 Gold Master 和更高版本上调用时,这会给出 EXC_BAD_ACCESS 。iOS 7 beta 6 及更早版本都可以。

在 iOS 7 中是否有其他方法可以做到这一点?

NSLog("%@", searchBarButton)结果在iOS7上:

2013-10-01 16:14:25.972 MP Staging[12293:a0b] <_UIBarItemAppearance:0x1aaf72d0> <Customizable class: UIBarButtonItem> when contained in ( UISearchBar ) with invocations (null)>

这在 iOS 6 上

<_UIBarItemAppearance: 0x1c671aa0>

4

3 回答 3

5

setTitle在 iOS7 中会失败。

尝试博客中的以下代码:

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    self.searchDisplayController.searchBar.showsCancelButton = YES;
    UIButton *cancelButton;
    UIView *topView = self.searchDisplayController.searchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
    }
    if (cancelButton) {
      //Set the new title of the cancel button
        [cancelButton setTitle:@"Annuller" forState:UIControlStateNormal];
    }
}
于 2013-10-01T20:38:25.383 回答
2

我在 7.1 中使用它没有任何问题,但是,它似乎在 7.0.x(设备和 sim)上崩溃 - 希望这意味着他们已经在 7.1 中恢复了该属性,但这也意味着我们必须使用上述子视图之一遍历临时版本的 hack。

    id barButtonAppearanceInSearchBar = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
    [barButtonAppearanceInSearchBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:15],
                                                             NSForegroundColorAttributeName : [UIColor blackColor]
                                                             } forState:UIControlStateNormal];
    [barButtonAppearanceInSearchBar setTitle:@"Done"];
于 2014-04-04T01:40:34.733 回答
1

UIBarButtonItemtitle属性不能通过UIAppearance代理获得。

我不知道为什么它在 iOS 6 中工作,但绝对不应该。

您似乎拥有的唯一选择是UISearchBar通过爬取其子视图以查找按钮并设置标题来“破解” ,但是:

  • 非常脆弱,因为对子视图结构的任何实现更改都会破坏您的代码
  • 它不是全球性的,您必须在任何UISearchBar实例上执行此操作

根据this answersearchDisplayControllerWillBeginSearch: ,您可以通过以下方法执行此“hack” UISearchDisplayDelegate

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
     [theSearchBar setShowsCancelButton:YES animated:NO];

    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];
    }
}
于 2013-10-01T20:40:39.347 回答