【问题标题】:How can I connect a storyboard UISearchBar to a programmatically created UISearchController?如何将故事板 UISearchBar 连接到以编程方式创建的 UISearchController?
【发布时间】:2016-06-02 19:41:56
【问题描述】:
我之前在UITableView 的标题视图中有一个searchController.searchBar,但我想添加按钮来更改显示的数组。现在我已经在我的故事板中添加了一个UISearchBar,我正试图弄清楚如何将它连接到我的UISearchController,以便我可以正确更新结果。然而,即使在最新的 XCode 中,我们在 IB 中仍然有 UIDisplayController。
我认为有两种方法可以解决这个问题,或者有一种方法可以连接它们,但我不知道,或者我只是使用 searchController 原生的 searchBar 并将它的框架转移到我想要的位置。我犹豫是否要尝试后者,因为 AutoLayout 对调整大小有好处。
【问题讨论】:
标签:
ios
xcode
swift
uitableview
【解决方案1】:
我总是在 44 磅高的界面构建器文件中放置一个占位符视图。然后,您可以将 SearchController.view 添加为该容器视图的子视图。
@IBOutlet weak var searchContainerView: UIView!
fileprivate lazy var searchController: UISearchController = {
let contactSearchViewController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: ContactSearchViewController.self)) as! ContactSearchViewController
contactSearchViewController.delegate = self
contactSearchViewController.datasource = self
let searchController = UISearchController(searchResultsController: contactSearchViewController)
searchController.searchResultsUpdater = contactSearchViewController
searchController.dimsBackgroundDuringPresentation = false
searchController.definesPresentationContext = true
return searchController
}()
override func viewDidLoad() {
super.viewDidLoad()
searchContainerView.addSubview(searchController.searchBar)
let attributes: [NSLayoutAttribute] = [.top, .bottom, . left, .right]
NSLayoutConstraint.activate(attributes.map{NSLayoutConstraint(item: self.searchController.searchBar, attribute: $0, relatedBy: .equal, toItem: self.searchContainerView, attribute: $0, multiplier: 1, constant: 0)})
}