一个 Viewcontroller 中的多个 collectionview 导致 Index out of range 错误

Posted

技术标签:

【中文标题】一个 Viewcontroller 中的多个 collectionview 导致 Index out of range 错误【英文标题】:Multiple collectionviews in one Viewcontroller causes Index out of range error 【发布时间】:2018-12-21 21:46:53 【问题描述】:

我尝试在一个视图控制器中使用三个集合视图。我像以下方法所示解析数据: 在底部,我根据位置将数据添加到右侧列表(这部分有效)

 func getEventData(eventIDs: [String], plz: String, positiona: Int)


        for eventId in eventIDs 
        let ref = Database.database().reference().child("Events").child(plz).child(eventId)
         ref.observe(.value, with:  snapshot in
            let item = snapshot.value as? [String: AnyObject]
            let eventName = item?["name"] as! String
            let date = item?["date"] as! String
            let lat = item?["lat"] as! String
            let lng = item?["lng"] as! String
            let infos = item?["additionalInfos"] as! String
            let position = item?["position"] as! String
            let ts = item?["ts"] as! Int
            let createdBy = item?["createdBy"] as! String

         let timestamp = NSDate().timeIntervalSince1970
            if (ts > Int(timestamp)) 
                let eo = EventObject(eventID: eventId, eventName: 
   eventName, info: infos, createdBy: createdBy, date: date, lat: lat, lng: lng, position: position, ts: ts)
                if positiona == 0
                    self.acceptedEvents.append(eo)
                    self.acceptedEventscv.reloadData()

                else if positiona == 1
                    self.myEvents.append(eo)
                    self.myEventscv.reloadData()

                else if positiona == 2
                   self.storedEvents.append(eo)
                self.storedEventscv.reloadData()
                
            

         )
        
    

在我的 NumbersofItemsInSection 方法中,我执行了以下操作:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    if collectionView == self.acceptedEventscv
    return acceptedEvents.count
    else if collectionView == self.storedEventscv
        return storedEvents.count
    else if collectionView == self.myEventscv
        return myEvents.count
    else
        return 0
    
    

在我的 CellForRowAtItem 方法中,我尝试了以下方法

func collectionView(_ collectionView: UICollectionView, 
 cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
 if collectionView == self.acceptedEventscv
 let cell = 
  collectionView.dequeueReusableCell(withReuseIdentifier: 
"acceptedEventsCell", for: indexPath) as! 
 acceptedEventsCollectionViewCell
 let eo = acceptedEvents[indexPath.row]
  cell.eventName.text = eo.eventName

  let items = eo.date!.components(separatedBy: " ")//Here replase 
  space with your value and result is Array.
 //Direct line of code
 //let items = "This is my String".components(separatedBy: " ")
 let date = items[0]
let time = items[1]
cell.date.text = date
cell.time.text = time

getUserNameAge(label: cell.usernameAge)
return cell
else 
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "savedEventsCell", for: indexPath) as! savedEventsCollectionViewCell
  let eo = acceptedEvents[indexPath.row]
  cell.eventName.text = eo.eventName

  let items = eo.date!.components(separatedBy: " ")//Here replase space with your value and result is Array.
  //Direct line of code
  //let items = "This is my String".components(separatedBy: " ")
  let date = items[0]
  let time = items[1]
  cell.date.text = date
  cell.time.text = time


  getUserNameAge(label: cell.usernameAge)

  return cell

问题是,如果我在第二个 CollectionView 中有更多项目,我总是会收到此错误:

线程 1:致命错误:索引超出范围

在这行代码:

let eo = acceptedEvents[indexPath.row]

【问题讨论】:

【参考方案1】:

cellForItemAt也一定是这样的

if collectionView == self.acceptedEventscv
  let item = acceptedEvents[indexPath.row]
   ----
  return cell
else if collectionView == self.storedEventscv
    let item = storedEvents[indexPath.row]   
    ----
    return cell
else 
     let item = myEvents[indexPath.row] 
     ----
     return cell  

在您的情况下,现在发生的情况是,在 numberOfItemsInSection 中返回的计数可能不同的两种情况下,您都访问了相同的数组 acceptedEvents

【讨论】:

以上是关于一个 Viewcontroller 中的多个 collectionview 导致 Index out of range 错误的主要内容,如果未能解决你的问题,请参考以下文章

返回上一个 ViewController 不适用于 Swift 中的多个视图控制器

使用多个 ViewController、Xcode 将代码连接到情节提要中的 UI

如何从一个 viewController 添加多个 segue

一个 Viewcontroller 中的多个 collectionview 导致 Index out of range 错误

如何在一个 viewController 上使用多个搜索栏来访问 Swift 中的不同 JSON 数据?

一个用于多个 ViewController 的网络处理程序类