在iOS7中更改取消按钮BackgroundColor和UISearchBar的文本

Ren*_*tti 1 iphone cocoa-touch objective-c uisearchbar ios7

我有以下代码更改UISearchBar中取消按钮的背景.

for( UIView *subview in self.searchBar.subviews ){
    if ([subview isKindOfClass:[UIButton class]]) {
        [(UIButton *)subview setEnabled:YES];
        [(UIButton *)subview setTitle:@"New Button Text" forState:UIControlStateNormal];
        ((UIButton *)subview).tintColor = [UIColor colorWithRed:4/255.0 green:119/255.0 blue:152/255.0 alpha:1.0];
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是这个代码在iOS7中不起作用!UISearchBar中视图结构发生了哪些变化?

编辑:在这里测试,这是UISearchBar的新层次结构:

UISearchBar:
---UIView:
------UISearchBarBackground
------UISearchBarTextField
------UINavigationButton
Run Code Online (Sandbox Code Playgroud)

问题是我无法测试if ([sub isKindOfClass:[UINavigationButton class]]).此行抛出编译错误:Use of undeclared identifier: UINavigationButton

Fir*_*ist 6

[Edited]

试试这个代码.

添加的AppDelegate,如果你想改变所有的取消按钮.

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                                      [UIColor redColor],
                                                                                                      UITextAttributeTextColor,
                                                                                                      [UIColor whiteColor],
                                                                                                      UITextAttributeTextShadowColor,
                                                                                                      [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                                                      UITextAttributeTextShadowOffset,
                                                                                                      nil]
                                                                                            forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

在iOS7中,我们需要添加 objectAtIndex:0 and subviews.

在iOS7中更改了searchBar子视图层次结构,请尝试以下操作:

in iOS7:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];


iOS6 and before:

NSArray *searchBarSubViews =  self.searchBar.subviews;
Run Code Online (Sandbox Code Playgroud)