【问题标题】:Custom CollectionViewCell handling button press自定义 CollectionViewCell 处理按钮按下
【发布时间】:2015-03-02 09:51:24
【问题描述】:

在我的应用程序中,我有一个自定义 collectionViewCell。我们称之为customCell。这个customCell 包含一个titleLabel、一个imageView 和两个按钮。我们称之为 tlLbl、imgView、btn1 和 btn2。

目标:如果我单击其中一个按钮,我想呈现一个新的 viewController。这个新的 viewController 应该得到 tlLbl 和 imgView 作为参数。我需要两者,因为我也会在新的 viewController 中显示标签和图像。

注意事项: 最简洁的解决方案是在 customCell 类中呈现新的 viewController。在这里传递参数不是问题。但无法更改 customCell 类中的视图。

好吧,没关系。下一个解决方案。我可以在我当前的 viewController 中处理按钮按下的动作。在 collectionView 委托函数“cellForItemAtIndexPath”中为 btn1 和 btn2 添加 GestureRecognizer 应该可以解决这个问题。哦不,这并不能解决问题。我当前的代码:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
   let customCell:customCellClass = collectionView.dequeueReusableCellWithReuseIdentifier("customCell", forIndexPath: indexPath) as customCellClass

   customCell.tlLbl.text="Test1"
   customCell.imgView.image=UIImage(named: "myImg.png")

   var tapRec = UITapGestureRecognizer(target: self, action: "btnTapped")
   var tapRec2 = UITapGestureRecognizer(target: self, action: "btnTapped2")

   customCell.btn1.addGestureRecognizer(tapRec)
   customCell.btn2.addGestureRecognizer(tapRec2)

   return customCell
}

//Btn tapped handler
func btnTapped() {
   let vc = newViewController() //change this to your class name
   self.presentViewController(vc, animated: true, completion: nil)
}

func btnTapped2() {
   let vc = newViewController2() //change this to your class name
   self.presentViewController(vc, animated: true, completion: nil)
}

问题:点击 customCell 中的按钮后,如何将 tlLbl 和 imgView 从 customCell 传递到新的 viewController。 UITapGestureRecognizer中的action参数

var tapRec = UITapGestureRecognizer(target: self, action: "btnTapped")

不允许传递你自己的参数。

我需要帮助。噗……

【问题讨论】:

  • 你能分享一下 UICollectionViewDataSource 的代码吗?这将有助于解决这个问题。 - 迪帕克
  • 数据源已共享?你的意思是“cellForItemAtIndexPath”函数吗?
  • numberOfItemsInSection 和 numberOfSectionsInCollectionView
  • 解决了这个问题。我必须编写自己的协议。

标签: swift ios8 uicollectionview cell uicollectionviewcell


【解决方案1】:

我只使用 numberOfItemsInSection 方法。它返回 jsonFiles 的计数。

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  return jsonParsedArr.count
}

jsonParsedArr 是一个包含 json 内容的数组。

对于 customCell,我创建了一个在“viewDidLoad”中注册的 nib 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2016-10-04
    • 2014-05-12
    相关资源
    最近更新 更多