OGeek|极客世界-中国程序员成长平台

标题: ios - UIViewController 中的多个初始化步骤问题(不能使用多重继承) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:34
标题: ios - UIViewController 中的多个初始化步骤问题(不能使用多重继承)

我正在尝试使用封装在另一个基类中的一些初始化步骤来实现 UIPageViewController。

由于在 Swift 中不可能实现多重继承,我正在尝试使用协议(protocol),但我想触发一些封装在基类中的初始化步骤。

Here是我写的基本 Controller 。

它封装了 Facebook Account Kit 插件以隐藏我的子 VC 不应该看到的连接信息(例如 import AccountKit 指令、AKFAccountKit 类实例)。

当我在标准类中使用它时,它可以工作:

class ClientViewController: AccountKitBaseViewController { /*...*/ }
extension ClientViewController: AccountKitBaseViewControllerDelegate {/*...*/}

但如果我将 PageVC 用作客户端类,我将无法使用它:

class ClientViewController: UIPageViewController, AccountKitBaseViewController { /* Error: Multiple inheritance from classes 'UIPageViewController' and 'AccountKitBaseViewController'*/ }
extension ClientViewController: AccountKitBaseViewControllerDelegate {/*...*/}

我怎样才能做到呢?



Best Answer-推荐答案


我想建议您将所有逻辑从 AccountKitBaseViewController 放到某个助手类中,并将此类的实例添加到您的 Controller 中。它将帮助您避免代码重复。您可以使用以下助手类:

class SocialNetworkAssistant {

    //Put here all required propertie from AccountKitBaseViewController
    public var delegate: AccountKitBaseViewControllerDelegate?
    public var isUserLoggedIn: Bool = false
    private var _accountKit: AKFAccountKit!
    private var _pendingLoginViewController: AKFViewController?

    //Put here all required methods from AccountKitBaseViewController
    public func accountKitLogout(completion: (() -> Swift.Void)? = nil) {

        guard isUserLoggedIn == true else { return }

        isUserLoggedIn = false
        _accountKit?.logOut()
        completion?()
    }

    // ... and so on
}

然后您可以将 SocialNetworkAssistant 的实例放入您的 Controller 中:

class ClientViewControllerFirst : UIViewController, AKFViewControllerDelegate {

    private let socialNetworkAssistantInstance = SocialNetworkAssistant()

    /* AKFViewControllerDelegate methods implementation */
}

class ClientViewControllerSecond : UIPageViewController, AKFViewControllerDelegate {

    private let socialNetworkAssistantInstance = SocialNetworkAssistant()

    /* AKFViewControllerDelegate methods implementation */
}

您也可以使用桥接模式。将 SocialNetworkAssistant 作为所有将实现 AKFViewControllerDelegate 而不是您的 Controller 的类的基类。然后,您将在 Controller 中使用 SocialNetworkAssistant 的不同子类。

关于ios - UIViewController 中的多个初始化步骤问题(不能使用多重继承),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169570/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4