[英]Protocols and delegate trouble in swift
所有,
我創建了一個swift文件,並在其中放入了一個協議,如下所示:
protocol PayButtonProtocol {
func enablePayButton()
func disablePayButton()
}
我已經使我的viewcontroller符合以下協議:
class ViewController: UIViewController, PayButtonProtocol
我也已經在ViewController中創建了函數,所以它看起來像這樣
func enablePayButton() {
println("Button enabled")
PAYBarButton.enabled = true
}
func disablePayButton() {
PAYBarButton.enabled = false
}
在另一個類中,我已經設置了委托,並且想要在按下這樣的命令時執行enablePayButton:
var delegate:PayButtonProtocol?
在功能中,我想通過以下方式執行功能之一:
delegate?.enablePayButton()
但它沒有執行,我想念什么?
代表很有可能是零。 添加斷點並在執行該行之前檢查委托的值。 還是更改“?” 改為“!” 如果委托為零,它將崩潰,讓您知道出了什么問題。
您在另一類中的代碼:
var delegate:PayButtonProtocol?
定義一個名為委托的變量,其類型為PayButtonProtocol?
。
變量delegate
將包含nil,直到您為其分配了一些東西:
delegate = <someObjectThatConformsToPayButtonProtocol>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.