UISearchBar宽度在嵌入UINavigationBar时不会改变 [英] UISearchBar width doesn't change when its embedded inside a UINavigationBar

查看:306
本文介绍了UISearchBar宽度在嵌入UINavigationBar时不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试新的 UISearchController iOS 8中引入的API虽然API是新的,但它使用相同的旧 UISearchBar 。我将它添加到 UINavigationController titleView

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)

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

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

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

它们都不起作用。

有没有人知道另一种方法吗?

Does anyone know another way to do this?

谢谢。

推荐答案

您可以使用其他视图作为导航栏标题并在其中放置搜索栏。如果出现条纹色彩问题,可以通过设置backgroundImage属性来解决。这应该工作:

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

这篇关于UISearchBar宽度在嵌入UINavigationBar时不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆