呈现搜索结果控制器时,UISearchBar的高度不正确

时间:2017-12-27 07:09:00

标签: ios swift uisearchbar uisearchcontroller uisearchresultscontroller

我在 tableView的标题视图中有一个搜索栏,我不会更改它的高度(默认为56pt)。当搜索栏处于活动状态并且其位置位于屏幕顶部时,它的高度变为50pt。它将在iPhone或模拟器iOS 11版本上发生。

首先出现:

<UISearchBar: 0x7f94b6646900; frame = (0 0; 375 56); text = ''; gestureRecognizers = <NSArray: 0x60400025fc20>; layer = <CALayer: 0x604000225fe0>>

编辑:

<UISearchBar: 0x7f94b6646900; frame = (0 14; 375 50); text = ''; autoresize = W+TM; gestureRecognizers = <NSArray: 0x60400025fc20>; layer = <CALayer: 0x604000225fe0>>

它导致搜索栏和结果控制器视图之间存在奇怪的差距。 gap

感谢任何想法。

EDIT1: 这是我的代码:

fileprivate func configSearchBar() -> Void {
    let bar = self.searchBar
    var size = bar.frame.size

    let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
    bar.setBackgroundImage(UIImage.imageWith(color: .white, size: size),
                           for: .any,
                           barMetrics: .default)
    let colorWhenEditing = UIColor.colorFromHexString("#FAFAFA")
    if UIDevice.isIPHONEX() {
        bar.barTintColor = colorWhenEditing
    } else {
        bar.setBackgroundImage(UIImage.imageWith(color: colorWhenEditing, size: CGSize(width: size.width, height: size.height + statusBarHeight)),
                               for: .topAttached,
                               barMetrics: .default)
    }
    size = CGSize(width: bar.frame.size.width - 30, height: 30)
    let image = UIImage.imageWith(color: UIColor(hexString: "#F0F0F0"), size: size)?.zoom(toSize: size, cornerRadius: 4)
    bar.setSearchFieldBackgroundImage(image, for: .normal)

    bar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}

self.tableView.tableHeaderView = self.searchBar

编辑2: - 搜索控制器和搜索栏初始化:

// Main view controller
lazy var searchResultController: UISearchController = {
    let vc = MailSearchResultViewController(nibName: nil, bundle: nil)
    let sc = UISearchController(searchResultsController: vc)
    sc.searchResultsUpdater = self
    sc.modalPresentationCapturesStatusBarAppearance = true
    sc.delegate = self
    return sc
}()
var searchBar: UISearchBar {
    return searchResultController.searchBar
}
// MailSearchResultViewController - viewDidLoad:
self.edgesForExtendedLayout = []
self.automaticallyAdjustsScrollViewInsets = false

2 个答案:

答案 0 :(得分:0)

我认为问题在于自动调整scrollView Insets。要解决此问题,请执行以下操作

  1. 转到故事板。
  2. 选择包含searchbarcontroller的控制器
  3. 转到属性检查器
  4. 取消选中“调整滚动视图插图”

答案 1 :(得分:0)

由于您正在使用iOS 11,并且从注释看起来您有导航控制器,您应该考虑将搜索栏直接放在导航项目中而不是表格视图标题中,这仍然是您应该使用的方法iOS 10及之前。您可以查看文档here

似乎自Apple推出这种显示搜索栏的新方式后,UIKit不再能够正确地从iOS 11及更高版本的表格视图标题中显示它。您还可以查看this question(在ObjC中)此相同更改引入相同问题或来自Apple的this video