UISearchBar: changing background color of input field
Asked Answered
T

5

7

I'm trying to change the background color of input field of UISearchBar.It's the rounded view where you input text to search, the default color is white. I would like to change it to gray

I tried:

for (UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
        UITextField *textField = (UITextField *)subView;
        [textField setBackgroundColor:[UIColor grayColor]];
    }

But it doesn't work :(

I also tried to insert an image view to TextField but it seems the rounded view is separate from TextField. So, any clues?

Tantalum answered 29/8, 2011 at 10:54 Comment(2)
u should create searchbar in code not in interfacebuilder.i had same issue while create from IB.so use code to create searchbarMidland
AHHHH, I did it! I set the textField.background with an image and it worked, yay!Tantalum
C
11

=)

for (UIView *subView in _searchBar.subviews) {
    for(id field in subView.subviews){
        if ([field isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)field;
            [textField setBackgroundColor:[UIColor grayColor]];
        }
    }
}
Celom answered 8/5, 2014 at 13:52 Comment(0)
E
7

Look at the function :

[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal];
Ely answered 12/10, 2012 at 8:33 Comment(0)
P
3

In Swift 2 and iOS 9 you can call:

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey()

Swift 3:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey()
Platy answered 10/5, 2016 at 5:30 Comment(1)
As @enreas mentioned, the solution is hence: https://mcmap.net/q/282578/-change-the-background-of-uisearchbar-39-s-textfieldTwosome
E
3

Solution in Swift 3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
}
Eupepsia answered 4/6, 2017 at 19:10 Comment(0)
H
0

Take the extension worked in swift4:

extension UISearchBar {

    var input : UITextField? {

        return findInputInSubviews(of: self)
    }

    func findInputInSubviews(of view: UIView) -> UITextField? {
        guard view.subviews.count > 0 else { return nil }
        for v in view.subviews {
            if v.isKind(of: UITextField.self) {
                return v as? UITextField
            }
            let sv = findInputInSubviews(of: v)
            if sv != nil { return sv }
        }
        return nil
    }
}

usage:

searchBar?.input?.layer.borderColor = color.cgColor
Herbage answered 8/11, 2018 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.