Swift 3:将SearchBar添加到UIViewController

时间:2017-06-07 02:24:29

标签: filter swift3 uicollectionview searchbar

我正在尝试将搜索/过滤器选项添加到Swift 3中的导航栏。目前,我正在从之前的视图推送到当前的UICollectionView,所有这些都在NavigationViewController堆栈上。

在当前的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区域中看到搜索栏。是否还需要设置其他内容才能显示?

1 个答案:

答案 0 :(得分:0)

您必须为frame指定UISearchBar。试试这个:

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
}