目标:要使搜索栏始终可见。
UISearchController
我做了什么:
问题:
预期行为:
问题
代码:
func setupSearchController() {
searchController.searchResultsUpdater = self
self.definesPresentationContext = false
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = true
let searchBar = searchController.searchBar
view.addSubview(searchBar)
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
searchBar.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
searchBar.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true
}
func presentSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
searchBar.removeFromSuperview()
let baseView = searchController.view
baseView.addSubview(searchBar)
searchBar.leadingAnchor.constraintEqualToAnchor(baseView.leadingAnchor).active = true
searchBar.trailingAnchor.constraintEqualToAnchor(baseView.trailingAnchor).active = true
searchBar.topAnchor.constraintEqualToAnchor(searchController.topLayoutGuide.bottomAnchor).active = true
self.presentViewController(searchController, animated: true) {
}
}
答案 0 :(得分:7)
我并没有完全遵循你的逻辑,但我能说的是你可以很容易地实现这一点。
UIView
将是容器
searchController
' searchBar
的约束,并将约束设置为
以下:UIView
与UIViewController
相关联,并将其命名为searchBarContainer UISearchController
属性:var searchController: UISearchController! = nil
幸运的是你的控制器看起来应该是这样的:(注意,这里我没有在这里实现代理,但你可以照顾它,因为这与动画无关:))
class SearchViewController: UIViewController {
var searchController: UISearchController! = nil
@IBOutlet weak var searchBarContainer: UIView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
self.searchBarContainer.addSubview(searchController.searchBar)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Setup the frame each time that the view appears in order to fit the width of the screen
// If you use autolayout just call searchController.searchBar.layoutIfNeeded()
var frame = searchController.searchBar.bounds
frame.size.width = self.view.bounds.size.width
searchController.searchBar.frame = frame
}
}
我的解决方案
iOS通讯录