简体   繁体   English

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

[英]Unable to change UISearchBar cancel button title color after changing it's text.

I'm using this code to change UISearchBar cancel button title: 我正在使用此代码更改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];
        }
    }
}
}

While changing the text works fine, changing the color doesn't. 虽然更改文本工作正常,但更改颜色不会。 It stays black. 它保持黑色。

I found the answer to this on SO a while back, but I don't recall where. 我在一段时间后找到了答案,但我不记得在哪里。 Here's the code that I'm using to set the color of the text. 这是我用来设置文本颜色的代码。

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

You can take advantage of the iOS Runtime Property _cancelButton to achieve this. 您可以利用iOS运行时属性_cancelButton来实现此目的。

UIButton *cancelButton = [self.searchDisplayController.searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitleColor:[UIColor yourColor] forState:UIControlStateNormal];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM