我正在按照本教程了解如何启动和运行 searchBar。
教程: https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
我完全按照所写的每一步进行操作,但是当我在手机上运行该应用程序时,按下搜索栏开始搜索某些内容,我遇到了一个名为“ fatal error :索引超出范围”的错误。这是导致错误的整个代码的代码
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return users.count
}else{
return self.locations.count
}
}
当我设置断点查看这个错误的原因时,它表明,当它到达
return self.locations.count
也就是错误发生的时候。如果有帮助,我可以发布更多我的代码
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]()
最佳答案
您的 collectionView(_:cellForItemAt:)
总是从 users
数组中返回项目。如果 locations
的元素多于 users
,它将尝试访问 users
数组中的无效索引。
collectionView(_:cellForItemAt:)
和 collectionView(_:numberOfItemsInSection:)
必须从同一个数组读取以填充您的 Collection View 。
看看你提到的教程中相应的 tableView(_:cellForRowAtIndexPath:)
。
关于ios - 索引超出范围发生在 searchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619726/