xcode - 委托(delegate)返回 nil

标签 xcode swift delegates protocols

我正在尝试快速使用协议(protocol)/委托(delegate),虽然我没有收到任何错误,但似乎我的委托(delegate)没有被创建。

这是我的代码

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()
    }

}

符合协议(protocol)的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")
    }

}

委托(delegate)返回 nil,这就是为什么我从来没有从 Class2 得到 println,只是不确定为什么它是 nil。

最佳答案

您必须在 GameViewController 中设置对 GameDetailsViewController 类的引用,当它应该显示时,并按以下方式将其设置为 delegate :

gameDetailsViewController.delegate = self

而且委托(delegate)不是 nil,当然是在 prepareForSegue 或您用来呈现其他 ViewController 的任何其他方法中设置引用。

关于xcode - 委托(delegate)返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29039795/

相关文章:

ios - 临时 UIImage 从不清除

ios - TI Sensortag,如何使用按钮?

ios - 无法使用 Swift 语法过滤器

ios - CKReference 列表更新

ios - 如何为 URLSessionDataTask 分配委托(delegate)?

c# - 如何把这个 Func 变成一个表达式?

xcode - 如果从build设置中删除了桥接 header ,如何恢复?

iphone - UIImage 到 BitmapContext

swift - 暗盒而不是自定义 tabBar 项目

iphone - 未访问委托(delegate)方法