UISearchBar自定义角落

我正在尝试创建一个这样的搜索栏:

在此处输入图像描述

但是我注意到我可能不得不用我自己的图像替换搜索栏,因为当我设置时搜索栏的角落出错了:

self.searchController.searchBar.layer.cornerRadius = 50 // I've tried other numbers besides this too with no luck self.searchController.searchBar.clipsToBounds = true 

在此处输入图像描述

如果我这样设置:

 self.searchController.searchBar.layer.cornerRadius = self.searchController.searchBar.bounds.height/2 

搜索栏如下:

在此处输入图像描述

这仍然不像图像中那样精确。

有没有办法用图像替换文本字段的左侧和右侧,这样我可以使用自定义搜索栏中的圆角?

这里的问题是你在UISearchBar上设置了角半径,而不是它里面的UITextField。 你可以做一些破解来获得UITextField,但这并不是真的值得推荐的。

正如您在问题中提到的,您需要使用自定义图像和此处显示的方法: https : //developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/#//apple_ref/doc/ UID / TP40007529-CH3-SW40

我正在使用此代码UISearchBar,但您可以将此代码与UISearchController一起使用。

  let searchBar = UISearchBar() searchBar.sizeToFit() searchBar.placeholder = "Search" navigationItem.titleView = searchBar if let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.textColor = UIColor.blue if let backgroundview = textfield.subviews.first { // Background color backgroundview.backgroundColor = UIColor.white // Rounded corner backgroundview.layer.cornerRadius = 14; backgroundview.clipsToBounds = true; } } 

这个在swift 3 iOS 10中为我工作:

  searchController.searchBar.layer.cornerRadius = 20 searchController.searchBar.clipsToBounds = true 

在此处输入图像描述