如何向现有协议添加自定义功能?

问题描述 投票:-1回答:2

我有一个UICollectionView,当我实现UICollectionViewDelegate时,我得到了Swift提供的功能,例如:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

在我的UICollectionViewCell中,我放置了关闭图标,并且我正在寻找一种添加自定义didCloseItemAt函数的方法,如下所示:

func collectionView(_ collectionView: UICollectionView, didCloseItemAt indexPath: IndexPath)

这可能吗?怎么样?

ios swift swift4 swift5 swift4.2
2个回答
0
投票

您可以扩展协议,并省去自己在任何地方编写协议的麻烦。

extension UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didCloseItemAt indexPath: IndexPath) { 
        // Write your code in here
    }
}

这是如此强大,现在您可以在符合UICollectionViewDelegate的任何对象中调用此方法,它将始终运行代码。您只需要编写一次!


-1
投票

您可以创建自己的协议,其中包括UICollectionViewDelegate。

protocol YourCollectionProtocol: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didCloseItemAt indexPath: IndexPath)
}

然后使用此协议代替UICollectionViewDelegate。

© www.soinside.com 2019 - 2024. All rights reserved.