Hide UISearchBar clear text button
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];
Swift 4
Adding to Alexander's answer and block user interaction on clear button:
To hide button:
searchBar.setImage(UIImage(), for: .clear, state: .normal)
To disable user interaction on the clear button, simply subclass UISearchBar
class CustomSearchBar: UISearchBar {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if view is UIButton {
return view?.superview // this will pass-through all touches that would've been sent to the button
}
return view
}
}
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
}
}
You need to get the textField of the Search Bar:
UITextField *textField = [searchBar valueForKey:@"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;
hope this help! =)