繁体   English   中英

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

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

我正在使用此代码更改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];
        }
    }
}
}

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

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

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

您可以利用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