协议未调用

时间:2015-10-06 08:10:12

标签: ios swift2

我创建了一个协议MainMenuDelegate。但它没有打电话。

在我的MainMenu

import UIKit
    @objc
    protocol MainMenuDelegate {
        optional func toggleLeftPanel()
       }
    class MainMenu: UIViewController {
        var delegate: DashBoard!

        override func viewDidLoad() {
            super.viewDidLoad()

            // Do any additional setup after loading the view.
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

        @IBAction func selectAction(sender:UIButton) {
                delegate?.toggleLeftPanel()
        }

    }

在DashBoard中

import UIKit
@objc

    protocol DashBoardDelegate {

    }
    class DashBoard: UIViewController {
        var delegate: MainMenu?
        var a : MainMenu!
        override func viewDidLoad() {
        self.a = MainMenu()
        self.a.delegate = self
        }
    }
    extension DashBoard : MainMenuDelegate
    {
        func toggleLeftPanel()
        {
            print("afgygfy")
        }
    }

1 个答案:

答案 0 :(得分:0)

Issue is in the way your are connecting and using your view controllers. I am sure you are not using the right object when calling delegate method.

I created a sample in playground and could manage to call the delegate method. The key lines here are last 4 lines which shows the usage of object. I am not creating a new MainMenu object and using the one which was created in the Dashboard. For storyboard sake I replaced view controller methods with my own methods.

@objc

protocol DashBoardDelegate {

}
class DashBoard: UIViewController {
    var delegate: MainMenu?
    var a : MainMenu!

    func dash() {
        self.a = MainMenu()
        self.a.delegate = self
    }
}

extension DashBoard : MainMenuDelegate
{
    func toggleLeftPanel()
    {
        print("afgygfy")
    }
}

@objc
protocol MainMenuDelegate {
    optional func toggleLeftPanel()
}
class MainMenu: UIViewController {
    var delegate: DashBoard!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func takeAction() {
        print(delegate)
        delegate?.toggleLeftPanel()
    }

}


var dash = DashBoard()
dash.dash()

var main = dash.a
main.takeAction()
相关问题