Can I remove the image on the left of an UISearchbar
and add a new image?
For a specific UISearchBar
instance.
Objective-C:
// Get the inner search field.
UITextField *searchField = (UITextField *)[searchBar valueForKey:@"searchField"];
// Hide the left search icon.
[searchField setLeftViewMode:UITextFieldViewModeNever];
// 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 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.
In swift 2.0 do this:
let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
textFieldInsideSearchBar.leftViewMode = UITextFieldViewMode.Never
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)
Replace the search bar icon with a 1x1 transparent image and offset the text position
UIImage *blank = [UIImage imageNamed:@"blank"];
[self.searchBar setImage:blank forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
self.searchBar.searchTextPositionAdjustment = UIOffsetMake(-19, 0);