UISearchBar width doesn't change when its embedded inside a UINavigationBar

落爺英雄遲暮 提交于 2019-12-21 17:32:05

问题


I'm experimenting with the new UISearchController API introduced in iOS 8. Although the API is new, it uses the same old UISearchBar. I added it to the UINavigationController's titleView.

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchController = UISearchController(searchResultsController: nil)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.delegate = self
        navigationItem.titleView = searchController.searchBar
    }
}

I don't need the search bar to take the entire width of the navigation bar. The problem is I can't resize it. First I tried setting the search bar's frame.

searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 100, height: 44)

That didn't work so I tried setting the titleView's frame.

navigationItem.titleView!.frame = CGRect(x: 0, y: 0, width: 100, height: 44)

Neither of them works.

Does anyone know another way to do this?

Thank you.


回答1:


You can use another view as navigation bar title and place search bar inside it. If bar tint color problem occurs, it can be solved by setting backgroundImage property. This should work:

let searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.delegate = self

let frame = CGRect(x: 0, y: 0, width: 100, height: 44)
let titleView = UIView(frame: frame)
searchController.searchBar.backgroundImage = UIImage()
searchController.searchBar.frame = frame
titleView.addSubview(searchController.searchBar)
navigationItem.titleView = titleView


来源:https://stackoverflow.com/questions/26722762/uisearchbar-width-doesnt-change-when-its-embedded-inside-a-uinavigationbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!