rac*_*ach 5 orientation uisearchbar swift uisearchcontroller
我一直在与UISearchController的搜索栏挣扎了很长一段时间.我需要在tableview上实现搜索功能,但与传统方法不同,我没有将搜索栏放在表头视图上.相反,我创建了一个UIView并将搜索栏添加为子视图.将UIView它作为一个容器来搜索栏有其正确的约束与自动布局故事板设置.
这是我的代码.请注意,我是以编程方式执行此操作的,因为UISearchDisplayController和UISearchBar从iOS 8开始已被弃用,而不是UISearchController,并且尚未来到UIKit.
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.autoresizingMask = .FlexibleRightMargin
searchController.searchBar.delegate = self
definesPresentationContext = true
self.searchContainerView.addSubview(searchController.searchBar)
Run Code Online (Sandbox Code Playgroud)
但是,我确实注意到旋转期间搜索栏的一个奇怪的行为.当它在纵向上处于活动状态时,我将模拟器旋转到横向,然后按取消,搜索栏将返回纵向宽度.
反过来也是如此.
我会很感激任何想法或者一些暗示正确的方向来解决这个问题,因为我至少已经在这几天了.非常感谢你
所以经过这么多天的努力:
人像风景
风景到Potrait
我终于自己解决了。似乎当用户在SearchBar上按Cancel时,ViewController将调用,viewDidLayoutSubviews因此我尝试通过在viewDidLayoutSubviews以下位置调用此函数来重置宽度:
func setupSearchBarSize(){
self.searchController.searchBar.frame.size.width = self.view.frame.size.width
}
Run Code Online (Sandbox Code Playgroud)
但这并没有我想象的那样好。所以这就是我想发生的事情。当用户激活SearchController / SearchBar时,SearchController会在调整其自身大小之前保存当前框架。然后,当用户按下“取消”或将其取消时,它将使用保存的框架并将其调整为该框架的大小。
因此,为了在单击“取消”时强制其宽度重新对齐,我必须在VC中实现UISearchControllerDelegate,并检测何时关闭SearchController,然后setupSearchBarSize()再次调用。
以下是解决此问题的相关代码:
class HomeMainViewController : UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var searchContainerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.autoresizingMask = .FlexibleRightMargin
searchController.searchBar.delegate = self
searchController.delegate = self
definesPresentationContext = true
self.searchContainerView.addSubview(searchController.searchBar)
setupSearchBarSize()
}
func setupSearchBarSize(){
self.searchController.searchBar.frame.size.width = self.view.frame.size.width
}
func didDismissSearchController(searchController: UISearchController) {
setupSearchBarSize()
}
override func viewDidLayoutSubviews() {
setupSearchBarSize()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2321 次 |
| 最近记录: |