I tried:
UITextField *searchtextfield = [searchBar.subviews objectAtIndex:1];
UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
cButt
Set clearButtonMode
to UITextFieldViewModeNever
and rightViewMode
to UITextFieldViewModeAlways
In swift 2.2, following code worked for me
[UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Normal)]
[UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Highlighted)]
You can hide your cancel button on searchBarTextDidBeginEditing
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
}
And the most amazing you can also hide you clear button by
UITextField *textField=(UITextField*)[[searchBar subviews]objectAtIndex:1];
textField.clearButtonMode=UITextFieldViewModeNever;
Follow my answer foe more info link
Swift
4.2, 4.1+ of malex answer,
UISearchBar.appearance().setImage(UIImage(named: "image1"), for: .clear, state: .normal)
UISearchBar.appearance().setImage(UIImage(named: "image2"), for: .clear, state: .highlighted)
I also answered this here to set clear button
tintColor
along with results button
customization.
If you want to set a custom clear button in a UISearchBar try this:
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"MyClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
Don't forget to set an image for UIControlStateHighlighted
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"HighlightedClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
You need the following
[searchBar setImage:[UIImage imageNamed:@"image1"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[searchBar setImage:[UIImage imageNamed:@"image2"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
It is strongly recommended to place strings in this order starting from UIControlStateHighlighted in case you want to use the same image: image1=image2=image.
In iOS7 it is weird but fact that direct order of UIControlStateNormal and UIControlStateHighlighted doesn't work.