2017-11-07 19 views
0

UICollectionViewの検索結果をフィルタリングできる検索バーを作成しようとしています。私は、検索がUICollectionViewUICollection Viewの検索バーが検索結果ではありません

func updateSearchResults(for searchController: UISearchController) 
     { 
      let searchString = searchController.searchBar.text 
      filtered = items.filter({ (item) -> Bool in 
       let countryText: NSString = item as NSString 
       return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound 
      }) 
      collectionView.reloadData() 
     } 

問題になりフィルタリング.FORストーリーボードの対応する要素は、その検索ではないですカスタムUICollectionViewCellクラス

class toolCollectionViewCell: UICollectionViewCell { 

    @IBOutlet weak var imageViewCell: UIImageView! 
    @IBOutlet weak var toolTitle: UILabel! 

} 

これらIBoutletsの両方がリンクされているを作りました正しく動作します。 検索結果は常にコレクションビューの最初の項目にフィルタリングされます。どのように検索を修正するには?プロジェクトdownloadすることができます。

答えて

0

あなたは、この方法では、セルのテキストに変更するのを忘れ:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! toolCollectionViewCell 

     //configureCell(cell: cell as! toolCollectionViewCell, forItemAtIndexPath: indexPath as NSIndexPath) 
     cell.imageViewCell=cell.viewWithTag(1) as! UIImageView 
     if searchActive { 
      cell.imageViewCell.image=imageViewArray[indexPath.row] 
      cell.toolTitle.text = filtered[indexPath.row] 
     } else { 
      cell.imageViewCell.image=imageViewArray[indexPath.row] 
      cell.toolTitle.text = items[indexPath.row] 
     } 
     return cell  //return your cell 
    } 

そして、これはイメージで動作しませんが。あなたは、料理名をキーとし、価値のあるイメージとして辞書を使用しなければなりません。また、タイトルフィールドとイメージフィールドを持つクラスフードのようなものを作成するのがよいでしょう。次に、このクラスをタイトルでフィルタリングします。

そして私もこの方法を変更:ここでは

func updateSearchResults(for searchController: UISearchController) { 
    // better way is to use "guard" or "if let searchString = searchString { ... }", 
    // because using searchString! could produce a crash in some cases. 
    guard let searchString = searchController.searchBar.text else { 
     return 
    } 

    filtered = items.filter({ (item) -> Bool in 
     let countryText: NSString = item as NSString 
     return countryText.lowercased.contains(searchString.lowercased()) 
    }) 

    collectionView.reloadData()   
} 

は、クラスや画像を例に取り組んでいる - Download

+0

検索は、クラスを作成し、画像の配列にデータメンバを追加する方法を動作していませんtitles.pleaseヘルプの配列? –

+0

@ajadka私はクラス – Eridana

+0

で私に付いている例をダウンロードしました。これは私が https://drive.google.com/file/d/18M2O5g5YrLlqtNVons6RsSsk6RkDpsl4/viewを提供したのと同じプロジェクトです。 –

関連する問題