Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the image on the left of an UISearchbar

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

like image 724
a111 Avatar asked Jul 14 '10 10:07

a111


6 Answers

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.

like image 73
Nick Toumpelis Avatar answered Nov 18 '22 04:11

Nick Toumpelis


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)
like image 40
Jeff Avatar answered Nov 18 '22 05:11

Jeff


// 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.

like image 35
Rostyslav Avatar answered Nov 18 '22 05:11

Rostyslav


In swift 2.0 do this:

let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
textFieldInsideSearchBar.leftViewMode = UITextFieldViewMode.Never
like image 10
Ciprian Rarau Avatar answered Nov 18 '22 05:11

Ciprian Rarau


Swift 4 Solution

searchBar.setImage(UIImage(), for: .search, state: .normal)
like image 8
iOS Lifee Avatar answered Nov 18 '22 03:11

iOS Lifee


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.

like image 7
Wolfshead Avatar answered Nov 18 '22 04:11

Wolfshead