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 solution :
extension UISearchBar{
var textField : UITextField{
return self.value(forKey: "_searchField") as! UITextField
}
}
Usage :
searchBar.textField.clearButtonMode = .never
thijsonline's answer in swift:
(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).clearButtonMode = .never
Tested on iOS 13
One liner working for me:
searchBar.searchTextField.clearButtonMode = .never
You can also set it to .whileEditing
to have it displayed when the user is typing and then removed when the search bar loses focus.
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
}
}
Try this:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
UITextField *textField = [searchBar valueForKey:@"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;
}
In Case of Swift 2.3 just use :
var searchBar = UISearchBar();
searchBar.frame = CGRectMake(0, 0, 00, 20))
for subview: UIView in (searchBar.subviews.first?.subviews)!
{
if (subview.isKindOfClass(UITextField) )
{
let textFieldObject = (subview as! UITextField)
textFieldObject.clearButtonMode = .Never;
}
}