繁体   English   中英

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

[英]How to open activity and pass variable on selection of collectionview cell?

我有一个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方法中,有一个我要尝试执行的示例,但代码不正确。 我想对英语到技术的所有单元格都这样做。 预先感谢您,如果您有任何疑问,请通知我!

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

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

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

并准备进行测试:

    vc.myInfo = Info(class_name2)

在viewDidLoad中填充您的UI:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM