索引超出范围+错误说明

时间:2017-08-23 00:21:43

标签: swift layout uicollectionview

我有一个View Controller,它有两个UICollectionViews,下面的代码可以在模拟器中正确显示所有内容。但是,当我尝试滚动第二个UICollectionView时,模拟器失败并收到致命错误:索引超出范围。它将此代码行显示为错误指令:

cell.ImageView.image = UIImage(named: Popu[indexPath.row])



import UIKit

class MainScreen: UIViewController, UICollectionViewDelegate, 
UICollectionViewDataSource {

@IBOutlet weak var TopCollectionView: UICollectionView!
@IBOutlet weak var BottmView: UICollectionView!

var theList = ["Stanford", "Cal", "Alabama", "USC"]

var Popu = ["Football", "Basketball", "Baseball", "Hockey"]


override func viewDidLoad() {
    super.viewDidLoad()

    TopCollectionView.dataSource = self
    TopCollectionView.delegate = self

    BottmView.dataSource = self
    BottmView.delegate = self


    let availableWidth = view.bounds.width - 8 - 4
    let itemSize = availableWidth / 2

    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 6, left: 4, bottom: 6, right: 4)
    layout.minimumInteritemSpacing = 4
    layout.minimumLineSpacing = 4
    layout.itemSize = CGSize(width: itemSize , height: itemSize)

    BottmView.collectionViewLayout = layout


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}



func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return theList.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView==self.TopCollectionView {

    let cell:TopImages = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! TopImages

    cell.myImage.image = UIImage(named: theList[indexPath.row])

    return cell

}
else
    {
    let cell:PopCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PopUCell", for: indexPath) as! PopCell

    cell.ImageView.image = UIImage(named: Popu[indexPath.row])
    return cell
    }
}

}

1 个答案:

答案 0 :(得分:0)

您正在返回一个计数,但您有两个集合。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView==self.TopCollectionView {
        return theList.count
    } else {
        return Popu.count
    }
}