如何从Swift中的另一个类访问collectionView

时间:2015-05-29 20:43:33

标签: ios class swift collectionview

我继承了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()//

  }

1 个答案:

答案 0 :(得分: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
}