如何在导航栏中更改titleView的大小。因为navigationBar

时间:2017-02-24 03:49:49

标签: ios swift navigationbar

我在我的navigation.titleView

中添加了一个搜索栏
    self.navigationItem.titleView = searchBar

还有一个带有title =“”

的BackBarButtonItem
    self.navigationItem.backBarButtonItem?.title = ""

但是Back ButtonSearchBar之间存在差距,如下所示: There're gap between Back Button and SearchBar

我认为差距出现在这里是因为title backBarButtonItem的空间(因为我的title为空“但是空间仍然存在)

所以我想问一下如何省略这个差距?我想让searchBar更靠近backBarIcon

非常感谢你!

编辑1: 我尝试更改searchBar的框架,但它不起作用

这是我的代码

    //Change searchBar's frame        
    let titleViewFrame = (searchController.searchBar.frame)
    searchController.searchBar.frame = CGRect(x: titleViewFrame.minX - 20.0, y: titleViewFrame.minY, width: titleViewFrame.width + 20.0, height: titleViewFrame.height)

1 个答案:

答案 0 :(得分:0)

class SearchBarContainerView: UIView {  
  let searchBar: UISearchBar  
  init(customSearchBar: UISearchBar) {  
    searchBar = customSearchBar  
    super.init(frame: CGRect.zero)  

    addSubview(searchBar)  
  }

  override convenience init(frame: CGRect) {  
    self.init(customSearchBar: UISearchBar())  
    self.frame = frame  
  }  

  required init?(coder aDecoder: NSCoder) {  
    fatalError("init(coder:) has not been implemented")  
  }  

  override func layoutSubviews() {  
    super.layoutSubviews()  
    searchBar.frame = bounds  
  }  
}  

class MyViewController: UIViewController {  
  func setupNavigationBar() {  
    let searchBar = UISearchBar()  
    let searchBarContainer = SearchBarContainerView(customSearchBar: searchBar)  
    searchBarContainer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)  
    navigationItem.titleView = searchBarContainer  
  }  
}