I would like to know how to hide or not display the UISearchBar
cross that appears in the textField
fo the UISearchBar
I have
Swift 3, based on @Alexsander answer:
searchBar.setImage(UIImage(), for: .clear, state: .normal)
You need to get the textField of the Search Bar:
UITextField *textField = [searchBar valueForKey:@"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;
hope this help! =)
Based on @Gines answer, here is the Swift version:
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
guard let firstSubview = searchBar.subviews.first else { return }
firstSubview.subviews.forEach {
($0 as? UITextField)?.clearButtonMode = .never
}
}
There's a better way to do this, and you don't have to use private APIs or traverse subviews to do it, so this solution is App Store safe.
UISearchBar has a built-in API for doing this:
[UISearchBar setImage:forSearchBarIcon:state]
The SearchBar icon key you want is UISearchBarIconClear, and you want the UIControlStateNormal state. Then give it a clear image for the image, and you're done.
So, it should look like this:
[searchBar setImage:clearImage forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
I tried different solutions about this issue, even the one selected in this post, but they didn't work.
This is the way I found to solve this issue:
UIView *subview = [[searchBar subviews] firstObject]; //SearchBar only have one subview (UIView)
//There are three sub subviews (UISearchBarBackground, UINavigationButton, UISearchBarTextField)
for (UIView *subsubview in subview.subviews)
{
//The UISearchBarTextField class is a UITextField. We can't use UISearchBarTextField directly here.
if ([subsubview isKindOfClass: [UITextField class]])
{
[(UITextField *)subsubview setClearButtonMode:UITextFieldViewModeNever];
}
}
Swift 2.3, based on @Alexsander answer:
searchBar.setImage(UIImage(named: "SearchClearIcon"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)
searchBar.setImage(UIImage(named: "SearchClearIcon"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)