当UISearchBar嵌入UINavigationBar中时,其宽度不会改变。

5
我正在尝试使用iOS 8中引入的新UISearchController API进行实验。尽管API是新的,但其使用了相同的旧的UISearchBar。我将它添加到了UINavigationControllertitleView中。

输入图像描述 输入图像描述

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
    }
}

我不需要搜索栏占据整个导航栏的宽度。问题是我无法调整它的大小。首先,我尝试设置搜索栏的框架。
searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 100, height: 44)

这没起作用,所以我尝试设置titleView的框架。

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

他们俩都不起作用。

有人知道其他方法吗?

谢谢。

1个回答

15

您可以使用另一个视图作为导航栏标题,并将搜索栏放置在其中。如果出现边框颜色问题,可以通过设置backgroundImage属性来解决。应该可以这样做:

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

非常好!谢谢。 - Isuru
工作得非常完美。谢谢! - Joe M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接