1
在我的應用程序中搜索不能正常工作,問題在於,我通過鍵入特定字母來搜索某個字符,但它沒有出現在collectionView中,它沒有用搜索到的項目重新載入collectionView 這裏是全班代碼搜索不能在swift中工作
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)
}
}
它不工作。 collectionView不會與搜索到的項目重新加載 –
請分享該類別的整體代碼 – techloverr
我發佈了代碼 –