我正在迅速使用。我试图创建一个collectionView segue以导致一个新的viewController。
我有一系列(假设有8个)不同的图像和标签作为collectionView中的一个数组,当选中时,我希望将用户发送到另一个视图控制器(有8种不同的可能性-每个单元格一个)。我已经能够构建应用程序,但是选择单元格的行为是错误的。
第一个被选择的单元格没有响应,然后下一个单元格发起了segue-但对先前选择的单元格没有反应!每次选择一个不同的单元格时,它都会选择到先前选择的单元格。谁能帮助我纠正此错误?
在youtube上使用了不同的教程之后,我分别使用了performSegue和pushViewController,但是每个解决了相同的问题。
要连接的各种视图控制器已在main.storyboard文件中分配了自己的StoryboardID。初始视图控制器嵌入在导航控制器中,并且每个要连接的新veiwcontroller已连接到主视图控制器的集合视图。
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet var CollectionView: UICollectionView!
// created an array for labels
let NamesForSectionTitles = ["Overview","Canopy trees","Mid-story trees","Understory plants","Birds","Mammals","Ferns","Butterflys"]
// created list of images to be loaded in the collectionview
let sectionIconImages: [UIImage] = [
UIImage(named: "IMG_8750_landscape_night")!,
UIImage(named: "IMG_8789_Trees")!,
UIImage(named: "IMG_2185_Tree_Olearia")!,
UIImage(named: "_MG_9528_Herb_Flower")!,
UIImage(named: "IMG_3654-")!,
UIImage(named: "IMG_9892-2")!,
UIImage(named: "IMG_9496_Ferns_crozier")!,
UIImage(named: "IMG_7707_Butterfly")!,
]
override func viewDidLoad() {
super.viewDidLoad()
// load the data sources and delegate
CollectionView.dataSource = self
CollectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return NamesForSectionTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->
UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.SectionTitle.text = NamesForSectionTitles[indexPath.row]
cell.sectionImages.image = sectionIconImages[indexPath.row]
return cell
}
// tells the collection view that upon selecting a cell, show the next UIView controller, as suggested in storyboard name (main.storyboard property) - tutoral from https://www.youtube.com/watch?v=pwZCksvXGRw&list=PLPUDRZDcNNsMdyfZVw4CJDT1Wu8cYx_6E&index=7&t=0s
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: NamesForSectionTitles[indexPath.row], sender: self)
}
}
查看者应该看到带有标签的图像视图,选中该标签后会将其带到新的收藏夹视图。
答案 0 :(得分:0)
无法发表评论,所以发表答案
我认为
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
引起了问题。
请尝试将该行更改为:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)