Glenn Tisman
Glenn Tisman

Reputation: 163

Swift filterContentForSearchText

The following Swift searchController code works fine.

func filterContentForSearchText(searchText: String) {
    searchResults = drugs.filter({ ( drugs: Drug) -> Bool in
    let nameMatch = drugs.name.rangeOfString(searchText, options:
    NSStringCompareOptions.CaseInsensitiveSearch)
 return nameMatch != nil
  })
}

The above Swift searchController.textSearch works for Drug.name. The structure for the array is:

struct Drug {
  let name:String
  let tumor:String
  let targets:String
  let dosing:String
  let note:String
  let chart:String
}

Some lines of the array are defined as:

Drug(name:"ABT-199 (Tivantinib)", tumor:"CLL Lymphoma", targets:"BCL-2, BCL2", dosing:"", note:"", chart:""), Drug(name:"Adcetris (Brentuximab vedotin)", tumor:"Anaplastic Large Cell Lymphoma Hodgkin's ALCL", targets:"[CD30]", dosing:"", note:"", chart:""), Drug(name:"Afinitor (Everolimus)", tumor:"Kidney Renal Hypernephroma Breast Brain Subependymal Giant Cell Astrocytoma (SEGA) tuberous sclerosis neuroendocrine pancreas (PNET)", targets:"[mTOR1][FRAP1]", dosing:"", note:"", chart:"")

I added a scope bar with just three buttons. I am perplexed on how in Swift to change the above:

func filterContentForSearchText(searchText: String) so that I may have the user choose the scope of interest from scopeButtonTitles = ["Drugs", "Tumor", "Target"] ?

Any help is appreciated.

Upvotes: 2

Views: 2402

Answers (1)

Aniket Bochare
Aniket Bochare

Reputation: 427

Look at this tutorial from Raywenderlich which explains how to use scope. I am copying th code snippet which might help you.

http://www.raywenderlich.com/76519/add-table-view-search-swift

func filterContentForSearchText(searchText: String) {
  // Filter the array using the filter method
  self.filteredCandies = self.candies.filter({( candy: Candy) -> Bool in
    let categoryMatch = (scope == "All") || (candy.category == scope)
    let stringMatch = candy.name.rangeOfString(searchText)
    return categoryMatch && (stringMatch != nil)
  })
}

Upvotes: 1

Related Questions