【问题标题】:How do I get a SearchBar in a TableView to look like the one in the Settings App如何让 TableView 中的 SearchBar 看起来像设置应用程序中的那样
【发布时间】:2018-04-09 20:31:26
【问题描述】:
在我的应用程序中,我有一个可搜索的 TableView,顶部有一个 SearBar。我添加了 SearchBar,通过 Interface Builder 将一个拖入,然后将我的 TableView 设置为 UISearchBarDelegate 并添加:
searchBar.delegate = self
这会产生以下外观
我想要的是我的 SearchBar 看起来像设置应用程序中的那个(每个 iOS 设备上预装的那个)
此外,单击时,它的行为有所不同,因为它会使视图的其余部分变灰并删除此处所示的标题
而我的 SearchBar 只打开键盘并在点击时显示光标。
我需要做什么才能实现这种特定的外观和感觉?
【问题讨论】:
标签:
ios
swift
uitableview
uikit
uisearchbar
【解决方案1】:
您可以通过以编程方式将 UISearchController 添加到 navigationBar 来轻松完成。使用代码创建 UISearchController :
let controller = UISearchController(searchResultsController: nil)
然后将其添加到navigationItem,
controller.searchResultsUpdater = self
controller.obscuresBackgroundDuringPresentation = false
controller.searchBar.placeholder = "Search Candies"
definesPresentationContext = true
if #available(iOS 11.0, *) {
navigationItem.searchController = controller
} else {
navigationItem.titleView = searchController.searchBar
}
信用:https://www.raywenderlich.com/157864/uisearchcontroller-tutorial-getting-started
【解决方案2】:
您可以通过创建UISearchBar 的子类来自定义它:
class CustomSearchBar: UISearchBar {
override init(frame:CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.placeholder = "Search"
// Color of the text field (in your case it should be gray)
self.barTintColor = yourGraySearchBarColor
// Color of the cursor (you don't need to change this if you want to stay with the default blue)
self.tintColor = UIColor.white
// Background color of you search bar
self.backgroundImage = UIImage(named: "SearchBarBG")
}
}
要设置搜索栏的背景颜色,您必须创建一个图像,这是一个只有您想要的颜色(在您的情况下为浅灰色)的正方形,大小无关紧要,我会将其设置为 20x20 像素。
可以通过在整个屏幕上方添加一个半透明的灰色UIView来使背景变暗(SearchBar除外,所以它需要在SearchBar下方)。如果您采用UISearchBarDelegate,则可以在searchBarTextDidBeginEditing(_ searchBar: UISearchBar) 函数中添加此叠加层,并在searchBarTextDidEndEditing(_ searchBar: UISearchBar) 函数中将其删除。