在我的应用程序中搜索工作不正常,问题是我通过键入特定字母来搜索字符,它不会出现在collectionView中,它不会重新加载带有搜索项目的collectionView 这是全班代码
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collection: UICollectionView!
var starWarsArray = [StarWars]()
var searchedCharacters = [StarWars]()
var searching = false
override func viewDidLoad() {
super.viewDidLoad()
collection.delegate = self
collection.dataSource = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.Done
parseStarWarsCSV()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
view.endEditing(true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
view.endEditing(true)
collection.reloadData()
} else {
searching = true
let lettersInSearch = searchBar.text!.lowercaseString
searchedCharacters = starWarsArray.filter({$0.name.lowercaseString.containsString(lettersInSearch) != nil})
collection.reloadData()
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collection.dequeueReusableCellWithReuseIdentifier("StarWarsCell", forIndexPath: indexPath) as? StarWarsCell {
var starWars: StarWars!
if searching {
starWars = searchedCharacters[indexPath.row]
cell.configureCell(starWars)
}else {
starWars = starWarsArray[indexPath.row]//grab each item from the array
cell.configureCell(starWars)
}
return cell
}else {
return UICollectionViewCell()
}
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searching {
return searchedCharacters.count
}
return starWarsArray.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(110, 110)
}
}
答案 0 :(得分:1)
使用
searchedCharacters = starWarsArray.filter({$0.name.lowerCaseString.containsString(lettersInSearch)})