UISearchController searchBar frame only resizes on first click

后端 未结 2 780
长情又很酷
长情又很酷 2020-12-21 15:37

I have just implemented a UISearchController in a regular UIViewController, and I have a kind of weird issue.

I have a UIView that is adapted exactly to the size I w

相关标签:
2条回答
  • 2020-12-21 16:35

    For me this didn't work, but I found a solution that I would like to share:

    Instead of putting the searchBar in a containerView, put a navigationBar in the containerView, and put the searchBar in this navigationBar. For me, the problem still exists at this point.

    But then I put a 1-pixel wide view as a navigationItem to the right of the navigationBar. From then it works all fine, the textfield of the searchBar didn't stretch anymore after the first selection.

    It is more of a hack instead of a good solution to an annoying bug(?), but for me this hack is acceptable as I already needed some margins on both side of the searchBar. Here is some code:

    //on init or viewDidLoad

    navigationBar = UINavigationBar(frame: .zero)
    
    let navigationItem = UINavigationItem()
    navigationItem.titleView = searchController.searchBar
    
    let leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: Design.margin, height: 1))
    leftView.backgroundColor = .clear
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftView)
    
    let rightView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: Design.margin, height: 1))
    rightView.backgroundColor = .clear
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightView)
    
    
    navigationBar.items = [navigationItem]
    
    containerView.addSubview(navigationBar)
    

    // setup frame sizes in your layout

    0 讨论(0)
  • 2020-12-21 16:39

    UISearchController's view behaviour is weird indeed, but there is a simple workaround.

    • Use an additional container view
    • put UISearchController's view inside
    • set UISearchController's view autoresizing mask to UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
    • set UISearchController's frame to container's view bounds

    At this point UISearchController.view won't resize beyond container.bounds.

    0 讨论(0)
提交回复
热议问题