简体   繁体   English

协议和委托麻烦迅速

[英]Protocols and delegate trouble in swift

All, 所有,

I have create a swift file and put a protocol in it, like this : 我创建了一个swift文件,并在其中放入了一个协议,如下所示:

protocol PayButtonProtocol {
    func enablePayButton()
    func disablePayButton()
}

I have made my viewcontroller conform to the protocol like this : 我已经使我的viewcontroller符合以下协议:

class ViewController: UIViewController, PayButtonProtocol

I have also created the functions in the ViewController so it conforms like this 我也已经在ViewController中创建了函数,所以它看起来像这样

func enablePayButton() {
        println("Button enabled")
        PAYBarButton.enabled = true
    }

    func disablePayButton() {
        PAYBarButton.enabled = false
    }

And in another class, I have set the delegate and I want to execute the enablePayButton when something is pressed like this : 在另一个类中,我已经设置了委托,并且想要在按下这样的命令时执行enablePayButton:

 var delegate:PayButtonProtocol?

and in the function i want to execute one of the functions by : 在功能中,我想通过以下方式执行功能之一:

delegate?.enablePayButton()

but it doesn't execute, what am I missing please ? 但它没有执行,我想念什么?

More than likely delegate is nil. 代表很有可能是零。 Add a breakpoint and check the value of delegate before that line executes. 添加断点并在执行该行之前检查委托的值。 Or change the "?" 还是更改“?” to a "!" 改为“!” and it will crash if delegate is nil, letting you know what's wrong. 如果委托为零,它将崩溃,让您知道出了什么问题。

Your code in the other class: 您在另一类中的代码:

var delegate:PayButtonProtocol?

defines a variable named delegate that is of type PayButtonProtocol? 定义一个名为委托的变量,其类型为PayButtonProtocol? .

The variable delegate will contain nil until you assign something to it: 变量delegate将包含nil,直到您为其分配了一些东西:

delegate = <someObjectThatConformsToPayButtonProtocol>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM