2017-06-25 11 views
3

下の画像のようにuicollectionビューの上に検索バーを配置したいと思います。私はプログラムでこれをやりたい enter image description here検索バーをuicollectionviewで使用する方法

現在のビュー

my implementation

これは、検索バーの設定機能のために私のコードです。私は家のビューコントローラでそれを持っています。

func setupSearchBar() { 

    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 64, width:UIScreen.main.bounds.width, height: 32)) 
    searchBar.barTintColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1) 
    searchBar.backgroundColor = UIColor.blue 
    searchBar.isTranslucent = true 
    searchBar.placeholder = "Search Timeline" 
    searchBar.searchBarStyle = UISearchBarStyle.prominent 
    view.addSubview(searchBar) 

} 

答えて

1

は、これらのコードを追加してください:

// Call sizeToFit() on the search bar so it fits nicely in the UIView 
    self.searchController!.searchBar.sizeToFit() 
    // For some reason, the search bar will extend outside the view to the left after calling sizeToFit. This next line corrects this. 
    self.searchController!.searchBar.frame.size.width = self.collectionView!.frame.size.width 
+0

どのようなUIViewControllerを検索コントローラに供給しますか? – jhaywoo8

+0

@ jhaywoo8 uは、setupSearchBar()関数内でsearchBar.sizeToFit()を追加しようとしている可能性があります。 –

0

あなたのUICollectionviewヘッダに検索バーを追加することができます。

これは、プログラム

lazy var searchBar : UISearchBar = { 
    let s = UISearchBar() 
     s.placeholder = "Search Timeline" 
     s.delegate = self 
     s.tintColor = .white 
     s.barTintColor = // color you like 
     s.barStyle = .default 
     s.sizeToFit() 
    return s 
}() 

次は、あなたのビューでヘッダビューを登録ロードでした検索バーを作成します。

collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerCellId") 

オーバーライドあなたのヘッダがになりたいの高さを定義するには、以下の方法。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 
    return CGSize(width: view.frame.width, height: 40) 
} 

最後に、全体のヘッダビューに合うように制約を定義、UICollectionviewヘッダに検索バーを追加します。

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerCellId", for: indexPath) 
     header.addSubview(searchBar) 
     searchBar.translatesAutoresizingMaskIntoConstraints = false 
     searchBar.leftAnchor.constraint(equalTo: header.leftAnchor).isActive = true 
     searchBar.rightAnchor.constraint(equalTo: header.rightAnchor).isActive = true 
     searchBar.topAnchor.constraint(equalTo: header.topAnchor).isActive = true 
     searchBar.bottomAnchor.constraint(equalTo: header.bottomAnchor).isActive = true 
    return header 
} 
関連する問題