Can I remove the image on the left of an UISearchbar
and add a new image?
In iOS 5.0+, you can customize the search bar image using
- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
in a specific instance of a UISearchBar or across a bunch using the UIAppearance
proxy.
To completely remove the icon, you can use the following lines of code:
Objective-C:
// Remove the icon, which is located in the left view
[UITextField appearanceWhenContainedIn:[UISearchBar class], nil].leftView = nil;
// Give some left padding between the edge of the search bar and the text the user enters
[UISearchBar appearance].searchTextPositionAdjustment = UIOffsetMake(10, 0);
Swift:
// Remove the icon, which is located in the left view
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).leftView = nil
// Give some left padding between the edge of the search bar and the text the user enters
UISearchBar.appearance().searchTextPositionAdjustment = UIOffsetMake(10, 0)
// hide magnifying glass
UITextField* searchField = nil;
for (UIView* subview in searchBar.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField*)subview;
break;
}
}
if (searchField) {
searchField.leftViewMode = UITextFieldViewModeNever;
}
This hides magnifying glass. Works well.
In swift 2.0 do this:
let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
textFieldInsideSearchBar.leftViewMode = UITextFieldViewMode.Never
Swift 4 Solution
searchBar.setImage(UIImage(), for: .search, state: .normal)
Or in Swift 4.0 the simple one-liner:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).leftViewMode = .never
NOTE: This will remove the left hand icon from ALL UITextFields
that are contained inside UISearchBars
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With