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

微笑、不失礼 提交于 2019-12-10 19:06:26

问题


I'm using this code to change UISearchBar cancel button title:

-(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.


回答1:


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];



回答2:


You can take advantage of the iOS Runtime Property _cancelButton to achieve this.

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


来源:https://stackoverflow.com/questions/22848930/unable-to-change-uisearchbar-cancel-button-title-color-after-changing-its-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!