2017-06-07 42 views
0

我想在Swift 3的導航欄中添加一個搜索/過濾器選項。目前,我正在從之前的視圖推送到當前UICollectionView,所有這些視圖都位於NavigationViewController堆棧上。Swift 3:將SearchBar添加到UIViewController

在當前UICollectionViewController,我已經設置了一個UISearchBar對象像這樣:

let searchBar: UISearchBar = { 
    let sb = UISearchBar() 
    sb.placeholder = "Enter search term" 
    return sb 
}() 

而且內部collectionViewController,viewDidLoad中()我建立如下:

// searchbar 
let navBar = self.navigationController?.navigationBar 
navigationController?.navigationBar.addSubview(searchBar) 


searchBar.anchor(top: navBar?.topAnchor, left: navBar?.leftAnchor , bottom: navBar?.bottomAnchor, right: navBar?.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0 ) 

錨固完成通過自定義擴展,儘管我不相信它會影響任何內容,但如下所示:

extension UIView{ 
    // anchor 
    func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?,paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat){ 

     translatesAutoresizingMaskIntoConstraints = false 

     if let top = top{ 
      self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true 
     } 
     if let left = left{ 
      self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true 
     } 
     if let bottom = bottom{ 
      bottom.constraint(equalTo: bottom, constant: paddingBottom).isActive = true 
     } 
     if let right = right{ 
      rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true 
     } 
     if width != 0{ 
      widthAnchor.constraint(equalToConstant: width).isActive = true 
     } 
     if height != 0{ 
      heightAnchor.constraint(equalToConstant: height).isActive = true 
     } 

    } 
} 

但是,當我加載相應的uicollectionviewcontrollers時,我無法在navigationController navBar區域中看到搜索欄。是否還有其他需要設置的內容才能顯示?

回答

0

您必須爲您的UISearchBar指定frame。試試這個:

let searchBar: UISearchBar = { 
    let sb = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44)) //change the width & height according to your needs. 
    sb.placeholder = "Enter search term" 
    return sb 
} 
相關問題