ios - 不同的类有相似的方法

标签 ios swift

假设我正在制作带有 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/

相关文章:

ios - AVAssetWriter:开始写入时的瞬间滞后

ios - 使用 PFUser.getCurrentUserInBackground() 时出错

ios - 重复间隔对于本地通知无法正常工作 (Swift)

ios - NSLayoutConstraint 将 View 固定到父 View 的底部边缘

ios - UITableView 在快速滚动时混合单元格背景颜色

ios - 我们如何知道 ios 应用程序是否在上次启动时崩溃了?

ios - 省略 UIColor.setFill() 错误消息?

swift - 我可以在 SKCamera 中制作无限滚动背景吗?

ios - 如何在 UITableViewCell 中实现 UIPageViewController

ios - 在新 Apple Watch Series 2 WatchOS 3 中使用 GPS