Search code examples
arraysswiftsearchuicollectionviewsearchbar

Search for an Array from a UICollectionView


I am making an app in which the user can search for the name of an image in a UICollectionView. Currently, the user can name each image, and the names get stored to an array called arrayOfName.

I have added a search bar where I can successfully test for its text using:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {


        if (searchText.lowercased() == "test") {


            print("TEST")

        }
}

and

func addImgNames() {
        for _ in 0...20 {
            imgNames.append("imageNames")
        }

    }

This is now the user names the images:

let arrayOfNames = defaults.object(forKey: "imageNames") as? [Optional] ?? [String]()

        if let nameOfImage = (arrayOfNames[imgCell]) {
          self.navigationItem.title = nameOfImage

In addition, the search bar delegate and the arrayOfNames function are in two sperate classes, which makes it that much more difficult.

How can I test for a name that is stored in the array?

Thanks!!


Solution

  • You should filter your array, for example:

    arrayOfNames.filter {$0.searchInfo.contains(searchText.lowercased())}
    

    And for accessing arrayOfNames, you can make it global, or just pass it if you change your view with a performWithSegue and a prepareForSegue.