Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling the cancel button in a UISearchBar

I have a UISearchBar that has a cancel button (it's displayed using -(void)setShowsCancelButton:animated). I've changed the tintColor of the search bar like this in an attempt to get a grayish searchbar:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; searchBar.tintColor = [UIColor colorWithWhite:0.8 alpha:1.0]; 

This is what it looks like now - notice how the cancel button is also gray: http://twitpic.com/c0hte

Is there a way to set the color of the cancel button separately so it looks more like this: http://twitpic.com/c0i6q

like image 944
Chu Yeow Avatar asked Jul 29 '09 13:07

Chu Yeow


2 Answers

You can use UIAppearance to style the cancel button without iterating subviews of the UISearchBar, but the UIButton header does not currently have any methods annotated with UI_APPEARANCE_SELECTOR.

EDIT: Drill down the subviews till you get that cancel button

But this usually returns nil until searchBar.setShowsCancelButton(true, animated: true) is called.

extension UISearchBar {  var cancelButton : UIButton? {     if let view = self.subviews.first {         for subView in view.subviews {             if let cancelButton = subView as? UIButton {                 return cancelButton             }         }     }     return nil } } 
like image 133
lemnar Avatar answered Sep 23 '22 16:09

lemnar


In iOS 5.0+, you can use the appearnce proxy.

Before the search bar is showed.:

UIBarButtonItem *searchBarButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil]; [searchBarButton setBackgroundImage:myCancelButtonImageNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [searchBarButton setBackgroundImage:myCancelButtonImageHighlighted forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault]; [searchBarButton setTitleTextAttributes:barButtonTitleTextAttributesNormal forState:UIControlStateNormal]; [searchBarButton setTitleTextAttributes:barButtonTitleTextAttributesHighlighted forState:UIControlStateHighlighted]; 

If you use [UIButton appearanceWhenContainedIn:[UISearchBar class], nil], it will affect other buttons (e.g. clear button). So, you'd better not use UIButton's appearnce. Try UIBarButtonItem.

like image 44
Yiming Tang Avatar answered Sep 19 '22 16:09

Yiming Tang