UISearchBar宽度不会改变,当它嵌入到UINavigationBar中时

问题描述:

我正在试验iOS8中引入的新的UISearchController API。虽然API是新的,但它使用的是旧的UISearchBar。我将它添加到UINavigationControllertitleViewUISearchBar宽度不会改变,当它嵌入到UINavigationBar中时

enter image description hereenter image description here

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) 

它们都不起作用。

有没有人知道另一种方式来做到这一点?

谢谢。

您可以使用另一个视图作为导航栏标题并在其中放置搜索栏。如果出现色块颜色问题,可以通过设置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 
+0

工程太棒了!谢谢。 – Isuru 2014-11-07 18:53:25

+0

同样在这里感谢您的帮助!工作很棒! :) – 2015-01-12 23:07:20

+0

工作完美。谢谢! – 2016-01-06 04:36:52