【问题标题】:Index out of range + Bad Instructions索引超出范围 + 错误指令
【发布时间】:2018-01-31 09:32:40
【问题描述】:

我有一个视图控制器,它有两个 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
    }
}

}

【问题讨论】:

  • 这不可能是全部代码。
  • @ryantxr 你是什么意思?我有这个代码和 Collection Cell 的 2 个子类。此代码运行,但当我尝试滚动 BottmView 时它崩溃。
  • 我现在看到了。我错过了它滚动。

标签: swift layout uicollectionview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2016-04-17
    • 2015-07-13
    相关资源
    最近更新 更多