UISearchBar: changing background color of input field

前端 未结 5 1726
夕颜
夕颜 2020-12-19 07:05

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 c

相关标签:
5条回答
  • 2020-12-19 07:36

    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
    
    0 讨论(0)
  • 2020-12-19 07:38

    Look at the function :

    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-19 07:39

    Solution in Swift 3:

    if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
            txfSearchField.borderStyle = .none
            txfSearchField.backgroundColor = .lightGray
    }
    
    0 讨论(0)
  • 2020-12-19 07:48

    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()
    
    0 讨论(0)
  • 2020-12-19 07:52

    =)

    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]];
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题