5

我正在试验UISearchControlleriOS 8 中引入的新 API。虽然 API 是新的,但它使用相同的旧UISearchBar. 我将它添加到UINavigationController.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
    }
}

我不需要搜索栏占据导航栏的整个宽度。问题是我无法调整它的大小。首先,我尝试设置搜索栏的框架。

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)

它们都不起作用。

有谁知道另一种方法来做到这一点?

谢谢你。

4

1 回答 1

15

您可以使用另一个视图作为导航栏标题并在其中放置搜索栏。如果出现 bar tint color 问题,可以通过设置 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
于 2014-11-07T14:28:21.757 回答