【问题标题】:Setting UISearchbar background color to white in IOS在IOS中将UISearchbar背景颜色设置为白色
【发布时间】:2021-03-23 09:33:50
【问题描述】:

我正在尝试更改 UISearchbar 的背景颜色。我可以将背景设置为除白色以外的任何颜色。不知道为什么白色没有设置。我正在使用下面的代码 sn-ps 来设置颜色。我有一个扩展方法来获取 textField。因此,您可以假设 textField 存在。

searchBar.backgroundColor = .white
searchBar.textField?.backgroundColor = .white

当我将它设置为白色时,它总是呈灰色。

但是,如果我使用白色以外的颜色,它会显示该颜色。

searchBar.textField?.backgroundColor = .blue

知道这里出了什么问题。

【问题讨论】:

  • 面临同样的问题!!

标签: ios swift uisearchbar


【解决方案1】:

试试这个:

if #available(iOS 13.0, *) {
    searchController.searchBar.textField.backgroundColor = .white
}

【讨论】:

    【解决方案2】:

    我创建了一个空白项目,其中我在中间引入了一个简单的搜索栏,并在viewDidAppear中写了如下代码:

        mySearchBar.barTintColor = .black
        
        mySearchBar.searchTextField.borderStyle = .roundedRect
        mySearchBar.searchTextField.backgroundColor = .white  //adapt the color here.
        
        mySearchBar.searchTextField.attributedPlaceholder =  NSAttributedString.init(string: "Searching for something?",
                                                                                     attributes: [NSAttributedString.Key.backgroundColor:UIColor.red,
                                                                                     NSAttributedString.Key.strokeColor:UIColor.black,
                                                                                     NSAttributedString.Key.foregroundColor:UIColor.black])
    

    ...以后得到结果:

    我自定义了不同搜索栏容器的背景颜色以便更好地理解。?
    根据这个原理,您可以根据需要在 iOS 中将 UISearchbar 背景颜色设置为白色。 ??

    【讨论】:

    • 我有相同的代码,但有些白色不起作用。我将创建一个新项目并尝试。
    • @Reshma:我是在 Xcode 12.3 和 iOS 14.2 下完成的。 ?如果您的应用程序中有相同的代码,那么您的代码中某处(包括您的搜索栏)中的某种代理外观可能会出现问题? ?
    • @Reshma:这个代码 sn-p 在没有其他代码的全新项目中工作吗?请随时通知我们。 ?
    • 我会回来的。尚未尝试新项目。
    【解决方案3】:

    我发现这样做的唯一可靠方法是将searchFieldText.borderStyle 设置为.none 并手动设置图层的cornerRadius 以匹配默认边框样式。比如:

    self.searchBar.searchTextField.borderStyle = .none
    self.searchBar.searchTextField.layer.cornerRadius = 10
    self.searchBar.searchTextField.backgroundColor = .white
    

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 1970-01-01
      • 2017-06-08
      • 2018-04-20
      • 2019-07-27
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      相关资源
      最近更新 更多