ios - 索引超出范围发生在 searchBar

标签 ios arrays swift uicollectionview

我正在按照本教程了解如何启动和运行 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/

相关文章:

c - 在 C 中对动态分配的可变长度字符串数组进行排序

Java:数组索引越界

swift - 无法访问 xctest 中的 toBlocking()

Swift build 总是在 Docker 中构建整个包

ios - 在 NSObject 中监听 UIView 的 touchesBegan/touchesEnded

objective-c - window addSubview释放问题

c++ - 将数组项移动 4 个位置

Swift - 如何刷新 NavigationController 菜单栏

ios - Xcode Scene Editor - 如何显示实体列表?

ios - 地标 kml 信息未显示在 iOS 版 Google 地球中