问题
I want to change tint color of Textfield to blue color and cancel button tint color of UISearchBar to white color.
I am using below code.
for (UIView *subView in searchBar.subviews)
{
for (UIView *ndLeveSubView in subView.subviews)
{
if([ndLeveSubView isKindOfClass:[UITextField class]])
{
[(UITextField *)subView setTintColor:[UIColor blueColor]];
}
else if ([ndLeveSubView isKindOfClass:[UIButton class]])
{
[(UIButton *)subView setTintColor:[UIColor whiteColor]];
}
}
}
But this changes both Textfield and cancel button's tint color to white. Can any one suggest another method for it?
Here's what I am getting...

The tint color of TextField is also White.....
回答1:
Try some thing like this:
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],UITextAttributeTextShadowOffset,nil] forState:UIControlStateNormal];
回答2:
UITextAttributeTextColor
Has been deprecated in the iOS 7 SDK. Use NSForegroundColorAttributeName
instead. Like so:
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil]
setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],NSForegroundColorAttributeName,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
If your UISearchBar is in a UINavigationBar - you can do this:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil]
setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whitecolor] ,NSForegroundColorAttributeName,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
回答3:
Please include this line below in your method-didFinishLanchingWithOptions:
[[UIBarButtonItem appearance] setBackgroundImage:[[UIImage imageNamed:@"Your image.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 12, 0, 12)] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
回答4:
[[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor whiteColor]];
来源:https://stackoverflow.com/questions/19651374/how-to-change-cancel-button-tint-color-of-uisearchbar-in-ios7