搜索栏文本字段背景颜色 swift

search bar text field background color swift

我在更改搜索栏文本字段的颜色时遇到问题。我尝试了很多变体来更改该颜色,但该文本字段的背景始终为灰色。关于如何解决它的任何想法?谢谢!

private func setupSearchBar(){
    searchBarOutlet.layer.cornerRadius = 6
    searchBarOutlet.layer.masksToBounds = true
    searchBarOutlet.layer.borderWidth = 1.5
    searchBarOutlet.layer.borderColor = UIColor.init(hexFromString: "7E5BEB").cgColor
    searchBarOutlet.isTranslucent = true
    if #available(iOS 13.0, *) {
        searchBarOutlet.searchTextField.backgroundColor = .white
        searchBarOutlet.searchTextField.tokenBackgroundColor = .white
        searchBarOutlet.searchTextField.tintColor = .clear
    } else {
        searchBarOutlet.textField.textColor = .black
        searchBarOutlet.textField.backgroundColor = .white
        searchBarOutlet.textField.tintColor = .white
    }
    searchBarOutlet.backgroundColor = .white
    searchBarOutlet.barTintColor = .white
    searchBarOutlet.setImage(#imageLiteral(resourceName: "Search icon"), for: .search, state: .normal)
}

您可以简单地将 UISearchBar 实例的 barTintColor 设置为您需要的颜色,即

searchBarOutlet.barTintColor = .white

并使用backgroundColor改变searchTextField

的背景颜色
searchBarOutlet.searchTextField.backgroundColor = .white

因此,下面的代码可以根据您的要求正常工作

searchBarOutlet.layer.cornerRadius = 6
searchBarOutlet.layer.masksToBounds = true
searchBarOutlet.layer.borderWidth = 1.5
searchBarOutlet.layer.borderColor = UIColor.init(hexFromString: "7E5BEB").cgColor
searchBarOutlet.isTranslucent = true
searchBarOutlet.barTintColor = .white
searchBarOutlet.searchTextField.backgroundColor = .white

截图: