委托返回 nil

Delegate returning nil

我正在尝试在 swift 中使用协议/委托,虽然我没有收到任何错误,但似乎我的委托没有被创建。

这是我的代码

Class 1

import UIKit

protocol GameViewSliding{
    func slideGameView()
}

class GameDetailsViewController: UIViewController {

    var delegate:GameViewSliding?

    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 showOptions(sender: AnyObject) {

        println("button pressed")
        println(delegate)
        delegate?.slideGameView()
    }

}

Class 2 符合协议

import UIKit

var currentHoleNumber:Int = 0
var parThree = false;
var parFive = false;

class GameViewController: UIViewController,  GameViewSliding{


var gameDetailsVC:GameDetailsViewController = GameDetailsViewController()
    override func viewDidLoad() {
        super.viewDidLoad()

        println("inside the game class")
        gameDetailsVC.delegate = self
    }

    func slideGameView(){
        println("this is from the root controller")
    }

}

代表返回 nil,这就是为什么我从来没有从 Class2 得到 println,只是不确定为什么它是 nil。

您必须在 GameViewController 中设置对 class GameDetailsViewController 的引用,并按以下方式将其设置为 delegate

gameDetailsViewController.delegate = self

当然,委托不是 nil,而是在 prepareForSegue 或您用来呈现另一个 ViewController.[=16 的任何其他方法中设置引用=]

我注意到在使用 SplitViewController 时设置委托时存在一些问题。来自 splitViewController 的 detailVC 可以像这样获取:

override func viewDidLoad() {
    super.viewDidLoad()
    let detailNavigationController = splitViewController?.viewControllers[1] as! UINavigationController
    let detailVC = detailNavigationController.topViewController as! DetailViewController

    detailVC.delegate = self
}

另一种方法是在 AppDelegate 中设置委托,配置 SplitViewController 后如下行:

let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let masterVC = masterNavigationController.topViewController as! MasterViewController
let detailNavigationController = splitViewController.viewControllers[1] as! UINavigationController
let detailVC = detailNavigationController.topViewController as! DetailViewController

detailVC.delegate = masterVC

我也遇到了这个问题。我已经检查过我已经实现了协议,让 VC 符合协议,创建该协议的委托。我唯一忘记做的是在将第二个 VC 的委托设置为第一个 VC.

时将标识符设置为 segue