gpt4 book ai didi

swift - 索引超出范围 + 错误指令

转载 作者:行者123 更新时间:2023-11-30 12:12:53 24 4
gpt4 key购买 nike

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

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
}
}

}

最佳答案

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

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

关于swift - 索引超出范围 + 错误指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com