Reputation: 155
I was following this tutorial on getting a searchBar up and running.
tutorial: https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
I followed every step exactly as written, but when I run the application on my phone, press the searchbar to begin searching something I run into an error called "fatal error: Index out of range". This is the code that is the entire code that is causing the error
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return users.count
}else{
return self.locations.count
}
}
When I set up breakpoints to see the cause of this error, it shows that when it reaches
return self.locations.count
that is when the error occurs. I can post more of my code if it will help
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PostCell
cell.backgroundColor = UIColor.clear
let postInformation = users[indexPath.row]
cell.userNameTextField.text = postInformation.user
cell.userDescription.text = postInformation.text
cell.postImage.loadImageUsingCachWithUrlString(urlString: postInformation.image!)
cell.cellLocationX = cell.postImage.frame.origin.x //cell.frame.origin.x
cell.cellLocationY = cell.postImage.frame.origin.y //cell.frame.origin.y
return cell
}
var users = [MapPoints]()
var locations = [MapPoints]()
Upvotes: 1
Views: 83
Reputation: 2477
Your collectionView(_:cellForItemAt:)
is always returning items from the users
array. If locations
has more elements than users
it will try to access invalid indices in the users
array.
collectionView(_:cellForItemAt:)
and collectionView(_:numberOfItemsInSection:)
must read from the same array to populate your collection view.
Have a look at the corresponding tableView(_:cellForRowAtIndexPath:)
in the tutorial you mentioned.
Upvotes: 1