假设我正在制作带有 UICollectionView
的可滚动页面.这些页面都是不同的,并由如下所示的 pages 数组填充:
let pages = [GreenPage(), YellowPage(), OrangePage(), YellowPage(), GreenPage()]
所以,为了澄清,会有一个绿色的页面,然后是黄色,然后是橙色......
现在,假设我想要让它在被点击时运行一个名为
tapped()
的函数。出现在每个 GreenPage()
, YellowPage()
, 和 OrangePage()
.现在,我看到这样做的唯一方法是:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let greenPage = collectionView.cellForItem(at: indexPath) as! GreenPage {
greenPage.tapped()
} else if let yellowPage = collectionView.cellForItem(at: indexPath) as! YellowPage {
yellowPage.tapped()
} else if let orangePage = collectionView.cellForItem(at: indexPath) as! OrangePage {
orangePage.tapped()
}
}
这似乎 super 多余。假设
tapped
是否还有其他方法可以做到这一点?每个类的函数都做同样的事情吗?
最佳答案
这是协议(protocol)的一个很好的例子。创造它
protocol Tappable {
func tapped()
}
采用协议(protocol)
class GreenPage : Tappable { ...
class YellowPage : Tappable { ...
class OrangePage : Tappable { ...
这减少了
didSelectItemAt
中的代码相当func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
(collectionView.cellForItem(at: indexPath) as? Tappable)?.tapped()
}
关于ios - 不同的类有相似的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60140386/