我有一个问题,我的当前配置是:
UITableViewController -> UINavigationController -> 一个可切换2个子视图控制器的视图控制器。
每个子视图控制器都有一个与之相关联的UISearchController。 当UISearchBar激活时,它似乎从未具有正确的位置。
extension MySearchViewController: UISearchControllerDelegate {
func willPresentSearchController(searchController: UISearchController) {
var adjustedOrigin = searchController.searchBar.frame.origin
//FIXME: There's some odd behavior with embedded child VCs where the status bar adjustments are not taken into consideration
adjustedOrigin.y += UIApplication.sharedApplication().statusBarFrame.height
searchController.searchBar.frame.origin = adjustedOrigin
definesPresentationContext = false
navigationController?.definesPresentationContext = true
navigationController?.extendedLayoutIncludesOpaqueBars = true
}
func didPresentSearchController(searchController: UISearchController) {
definesPresentationContext = true
}
func didDismissSearchController(searchController: UISearchController) {
var adjustedOrigin = searchController.searchBar.frame.origin
//FIXME: There's some odd behavior with embedded child VCs where the status bar adjustments are not taken into consideration
adjustedOrigin.y -= UIApplication.sharedApplication().statusBarFrame.height
searchController.searchBar.frame.origin = adjustedOrigin
}
}
您可以从上面看到,我试图手动更正UISearchBar的偏移量,这远非理想。我已经尝试在storyboard和代码中的多个区域中取消勾选 从而取消显示,但几乎在整个层次结构中都找不到偏移源头。默认情况下,UISearchBar将显示在状态栏下方:
这是没有我的手动调整的情况下,但仍然有些偏差。
有人有解决方法吗?
编辑1:
进一步证明某个父VC中的内容正在干扰偏移量,实际上UISearchBar的superView的偏移量为-20。因此,以下操作纠正了此问题:
import UIKit
class MySearchController: UISearchController {
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = .Top
extendedLayoutIncludesOpaqueBars = true
automaticallyAdjustsScrollViewInsets = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(active)
if active && searchBar.superview!.frame.origin != CGPoint.zero {
searchBar.superview?.frame.origin = CGPoint.zero
}
}
}