我在一个UIViewController中有两个单独的UICollectionViews。每个UICollectionView都从两个不同的数组中提取数据并正确显示它们。但是,我无法单击UICollectionViewCell来执行对另一个UIViewController的设置。
我认为它与if-else语句有关,因为我收到一条错误消息,指出“将永远不会执行。”
我尝试将“ didSelectItem indexPath”代码移至if-else语句之前和之后的不同部分。
导入UIKit
HomeViewController类:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
@IBOutlet weak var categoriesCollectionView: UICollectionView!
@IBOutlet weak var popularCollectionView: UICollectionView!
let categories = [
"Browse All Categories",
"cat1",
"cat2",
"cat3",
]
let categoryImages: [UIImage] = [
UIImage(named: "img1")!,
UIImage(named: "img2")!,
UIImage(named: "img2")!,
]
let browsePopular = [
"pop1",
"pop2",
"pop3",
]
let popularImage: [UIImage] = [
UIImage(named: "popImg1")!,
UIImage(named: "popImg2")!,
UIImage(named: "popImg3")!,
]
let browsePopularDescription = [
"popDesc1",
"popDesc2",
"popDesc3"
]
override func viewDidLoad() {
super.viewDidLoad()
categoriesCollectionView.delegate = self
categoriesCollectionView.dataSource = self
popularCollectionView.delegate = self
popularCollectionView.dataSource = self
///我尝试在开始时移动didSelect代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let name = categories[indexPath.row]
let viewController = storyboard?.instantiateViewController(withIdentifier: name)
self.navigationController?.pushViewController(viewController!, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
///开始分类收集查看代码
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView==self.categoriesCollectionView{
return categories.count
}
else{
return browsePopular.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView==self.categoriesCollectionView {
let cell: CategoriesCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellBrowseAll", for: indexPath) as! CategoriesCollectionViewCell
cell.categoriesCollectionViewImage.image = categoryImages[indexPath.item]
return cell
}
else{
let cell: PopularCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellPop1", for: indexPath) as! PopularCollectionViewCell
cell.browsePopular.text = browsePopular[indexPath.row]
cell.popularImage.image = popularImage[indexPath.row]
cell.browsePopularDescription.text = browsePopularDescription[indexPath.row]
return cell
}
///我尝试在末尾添加didSelect代码,但收到一条警告消息,内容为:“将永远不会执行”
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let name = categories[indexPath.row]
let viewController = storyboard?.instantiateViewController(withIdentifier: name)
self.navigationController?.pushViewController(viewController!, animated: true)
}
}
预期结果-用户单击UICollectionViewCell并使用
选择到新的UIViewController实际结果-无法识别点击或代码未执行