注销代表无法正常工作

时间:2016-12-12 15:36:03

标签: ios swift delegates swift-protocols

我有一个应用程序,其中包含一个中央视图控制器,在滚动视图中有3个子视图控制器,代表应用程序的各个部分。我的应用程序的一般流程如下

LoginVC -> AppVC [Settings, Inbox, Email]

我目前在我的设置视图控制器中有我的注销按钮,但实际的注销功能需要在AppVC中。我试过实现一个委托,但似乎无法让它正常工作

class Settings: UIViewController {
    var delegate: LogoutDelegate?

    @IBAction func logout(_ sender: Any) {
       delegate?.logoutOfApp()
    }
}

protocol LogoutDelegate: class {
    func logoutOfApp() 
}

----------------------------------

class AppVC: UIViewController, LogoutDelegate {
      func logoutOfApp() {
         print("This should be called")
         //Execute logout code
      }
}

任何人都可以帮我弄清楚为什么我的委托功能没有在我的AppVC中调用吗?

更新

这是我在滚动视图中设置子视图控制器的方法

func setupViews() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let settingsVC = storyboard.instantiateViewController(withIdentifier: "SettingsVC")
        let inboxVC = storyboard.instantiateViewController(withIdentifier: "InboxVC")
        let emailVC = storyboard.instantiateViewController(withIdentifier: "EmailVC")

        let viewControllers = [settingsVC, inboxVC, emailVC]

        let width = scrollView.bounds.width
        let height = scrollView.bounds.height

        scrollView.contentSize = CGSize(width: width * 3, height: height)

        var idx = 0

        for vc in viewControllers {
            addChildViewController(vc)
            let originX = CGFloat(idx) * width
            vc.view.frame = CGRect(x: originX, y: 0, width: width, height: height)
            scrollView.addSubview(vc.view)
            vc.didMove(toParentViewController: self)
            idx += 1
        }

        scrollView.setContentOffset(CGPoint(x: width, y: 0), animated: false)

    }

我不知道在哪里设置我的代表。我试图在我的for循环self.delegate = vc中设置它,但总是得到相同的错误,无法设置委托

1 个答案:

答案 0 :(得分:0)

问题是您从未设置委托,否则委托将始终为nildelegate?.logoutOfApp()将不会被执行。

AppVC中,您需要执行以下操作:

override func viewDidLoad() {
    super.viewDidLoad()

    settings.delegate = self
}