【问题标题】:How to access collectionView from a different class in Swift如何从 Swift 中的不同类访问 collectionView
【发布时间】:2015-05-29 20:43:33
【问题描述】:

如果我添加了不同的标签、动画和按钮,我将 CollectionViewCell 子类化。

我正在尝试在此类 (CollectionViewCell) 中的一个方法中删除一个单元格并更新 collectionView,但我无法从此处访问 collectionView,因为它是在另一个类/viewController 中声明的。

我的 CollectionView 类:

//this is how I have declared the collectionView.
class FirstViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

@IBOutlet weak var collectionView: UICollectionView!
}

我的 CollectionViewCell 类:

//this is what I'm trying to achieve although I know it's incorrect.
class CollectionViewCell: UICollectionViewCell {

func handlePanGesture(recognizer: UIPanGestureRecognizer) {

 FirstViewController.collectionView.reloadData()//

  }

【问题讨论】:

  • 最好让控制器成为手势识别器的目标。单元格类不应该知道集合视图,也不应该负责删除单元格——这是控制器的工作。

标签: ios class swift collectionview


【解决方案1】:

就像@rdelmar 所说,最好将 panGestureRecognizer 放入控制器中。

然后你就可以用collectionView.indexPathForItemAtPoint(recognizer.locationInView(collectionView))访问indexPath了

否则,您可以将 NSNotificationCenter 用于:

NSNotificationCenter.defaultCenter().postNotification(name: "CellPanned", object: recognizer)

在控制器中

NSNotificationCenter.defaultCenter().addObserver(self,selector:"cellPanned:" name: "CellPanned")

然后实施:

func cellPanned(notification:NSNotification) {
    let gestureRecognizer = notification.object as! UIPanGestureRecognizer
    // Handle pan
}

【讨论】:

  • hm,我不能将手势识别器放在 FirstViewController 中,因为识别器使用了一些在此类中声明和连接的 NSLayoutConstrains。我会尝试第二个选项并回帖。
  • 看起来它正在工作,但我将如何访问 func cellPanned(notification:NSNotification) { } 中的 indexPath?
  • 同方法一:collectionView.indexPathForItemAtPoint(recognizer.locationInView(collectionView))
  • 在有趣的 cellPanned 中没有“识别器”变量,我在该方法中只有“通知”变量,我很难弄清楚如何从通知中获取视图中的位置。识别器仍在 CollectionViewCell 类中,因为正如我之前所说,由于我在 collectionViewCell 上执行的其他变量和约束,我必须将它放在那里......
  • 当您在每次调用 didPan: 时使用 NSNotificationCenter.defaultCenter().postNotification(name: "CellPanned", object: recognizer) 发布通知时,识别器将是 notification.object
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
相关资源
最近更新 更多