Removing the image on the left of an UISearchbar

Viewed 28450

Can I remove the image on the left of an UISearchbar and add a new image?

20 Answers

Swift 4 Solution

searchBar.setImage(UIImage(), for: .search, state: .normal)

Swift 4 solution:

searchBar.setImage(UIImage(), for: .search, state: .normal)

You probably also want to adjust the gap on the left side:

searchBar.setPositionAdjustment(UIOffset(horizontal: -20, vertical: 0), for: .search)

I tried all answers on iOS 12 and 13 - and none worked correctly on both versions. The only correct answer is below:

searchField.leftViewMode = .never
if #available(iOS 13.0, *) {
    searchTextPositionAdjustment = UIOffset(horizontal: -20, vertical: 0);
}

You can use

searchBar.setImage(UIImage(), for: .search, state: .normal)

In Swift to remove search icon use this:

searchBar.setImage(UIImage(), for: .search, state: .normal)

To replace with custom image change UIImage() on your 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];
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: textfield.frame.size.height))
textfield.leftView = paddingView
textfield.leftViewMode = .always

This solution removes the magnifying glass as well as the padding.

swift 5.0, xCode 12 you can do next:
searchBar.setImage(UIImage(), for: .search, state: .normal)

Related