在 Swift 中覆盖 UICollectionView 函数

问题描述

我的应用程序中有一个振动功能,我想在我的应用程序中每个 collectionView 的每个“didHighlight”函数中触发它。

func collectionView(_ collectionView: UICollectionView,didHighlightItemAt indexPath: IndexPath) {
     softVibrate()
}

问题是我如何在一个地方覆盖这个 didHighlight 委托函数,这样就不需要手动为每个集合视图单独调用它?

搜索了这个,但找不到任何答案。

解决方法

您可以创建一个类,例如符合 NSObject 和 UICollectionViewDelegate 的 VibratedCollectionViewDelegate:

class VibratedCollectionViewDelegate: NSObject,UICollectionViewDelegate {}

并在您的新类中覆盖此方法。 然后应该在 yourViewContoller 中设置:

class MyViewController: UIViewController {

  let collectionView = UICollectionView()
  let vibratedCollectionViewDelegate = VibratedCollectionViewDelegate()

  override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.delegate = vibratedCollectionViewDelegate
    }

}

如果您需要额外覆盖 UICollectionViewDelegate 方法,您可以创建一个继承 VibratedCollectionViewDelegate 的新类。