更改文本后,无法更改UISearchBar取消按钮标题颜色.

Shi*_*iim 3 iphone objective-c uiview uisearchbar ios

我正在使用此代码更改UISearchBar取消按钮标题:

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
self.searchDisplayController.searchBar.showsCancelButton = YES;
UIView* view=_otsinguRiba.subviews[0];
for (UIView *subView in view.subviews) {
    if ([subView isKindOfClass:[UIButton class]]) {
        UIButton *cancelButton = (UIButton*)subView;

        if (cancelButton) {
        [cancelButton setTitle:@"Test") forState:UIControlStateNormal];
        [cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

虽然更改文本工作正常,但更改颜色不会.它保持黑色.

Bri*_*len 10

我在一段时间后找到了答案,但我不记得在哪里.这是我用来设置文本颜色的代码.

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