如何在选择collectionview单元格时打开活动并传递变量?

时间:2019-07-07 01:58:49

标签: ios swift uicollectionview uicollectionviewcell

我有一个collectionView,我正在使用显示图像和标签的自定义单元格。我正在用数组填充视图。当选择一个单元格时,我希望打开一个新活动并传递该类的名称。 这是我的代码:

class CollectionViewController: UICollectionViewController {
let classes = ["English","Math","Science","Social Studies","Other","Technology"]
let class_images : [UIImage] = [
    UIImage(named: "English")!,
    UIImage(named: "Math")!,
    UIImage(named: "Science")!,
    UIImage(named: "Social Studies")!,
    UIImage(named: "Other")!,
    UIImage(named: "Technology")!
]
override func viewDidLoad() {
    super.viewDidLoad()
  var layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.sectionInset = UIEdgeInsets(top: 22, left: 22, bottom: 22, right: 22)
    layout.minimumInteritemSpacing = 22
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return classes.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "class_cell", for: indexPath) as! custom_class_cell
    cell.class_name.text = classes[indexPath.item]
    cell.class_image.image = class_images[indexPath.item]
    // Configure the cell
cell.layer.borderWidth = 1.0
    cell.layer.borderColor = UIColor.black.cgColor
    return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 //This isn't the right code, but an example of what I want to do!
 if (indexPath=1){
 let vc = self.storyboard?.instantiateViewController(withIdentifier: 
 "classes")
                self.present(vc!, animated: true, completion: nil)
 //I want to pass this string to the class
 let class_name2 = "English"
 }
 else if(indexPath=2){
 let vc = self.storyboard?.instantiateViewController(withIdentifier: 
 "classes")
                self.present(vc!, animated: true, completion: nil)
 //I want to pass this string to the class
 let class_name2 = "Math"
 //it keeps going through the technology cell
  }

}

didSelectItemAt方法中,有一个我尝试执行的操作的示例,但是代码不正确。我想对英语到技术的所有单元格都这样做。预先谢谢您,如果您有任何疑问,请通知我!

2 个答案:

答案 0 :(得分:0)

最简单的方法: 在dest控制器中(假设是一个DetailController实例) 您应该拥有:

class DetailController...
...    var myInfo : MyInfo?

(MyInfo应该包含您要传递的所有数据。)

并准备好进行搜索:

    vc.myInfo = Info(class_name2)

在viewDidLoad中填充用户界面:

override func viewDidLoad() {
        super.viewDidLoad()
        self.detail.text = self. myInfo....

答案 1 :(得分:0)

这实际上是一个非常简单的解决方案,我只是太复杂了!

 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   let valueToPass = classes[indexPath.row]

单击该单元格后,您将获得每个班级的名称。之后,只需准备segue方法即可。