UISearchBar 的最小化样式具有透明背景。

11

我已经将一个 UISearchBar 添加到了一个 UITableView 的顶部。

        // init search bar
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        controller.searchBar.tintColor = Config.grayColor()
        controller.searchBar.searchBarStyle = UISearchBarStyle.Minimal

        self.tableView.tableHeaderView = controller.searchBar

        // set content offset for table view in order
        // that the searchbar is hidden at the beginning
        self.tableView.contentOffset = CGPoint(x: 0, y: controller.searchBar.frame.size.height)

        return controller
    })()
这基本上看起来像是预期的:

enter image description here

但当我输入搜索文本字段并向下滚动表视图时,它看起来很奇怪。搜索控制器的背景是透明的。

enter image description here

我尝试过设置barTintColorbackgroundColor,但没有任何效果。


这个有更新了吗? - Pouria Almassi
https://dev59.com/Abbna4cB1Zd3GeqPUw9W - Alberto Marturelo
4个回答

2

将搜索栏的背景颜色设置为白色

searchBar.backgroundColor = UIColor.white


欢迎来到StackOverflow并感谢您的帮助。您可以通过添加一些解释使您的答案更好。 - Kenzo_Gilead

2

我尝试了几乎所有方法,唯一对我有效的方式是:

searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.setBackgroundImage(UIImage(color: .white), for: UIBarPosition(rawValue: 0)!, barMetrics:.default)

这适用于“普通”和“演示”形式。 UIImage(color: .white) 只是创建一个1x1彩色图像以填充背景的一种方式。你可以在这里找到实现(链接)

0
你可以使用这段代码。这对我有效:
UITextField.appearance(whenContainedInInstancesOf:  
      [UISearchBar.self]).backgroundColor = UIColor.RGB(red: 230, green: 230, blue: 230)

UISearchBar有一个UITextField属性,您可以像上面那样更改该颜色。


0
在Swift 5中,对我有效的唯一解决方案是:
func viewDidLoad() {
  // make content disappear when it touches searchBar
  edgesForExtendedLayout = []

  // make searchBar color non-transparent
  searchBarController.searchBar.backgroundColor = .red
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接