2015-01-09 31 views
10

我有一個委託,我想在按鈕按下時在GameController中調用numpadView(numpadView :)的視圖,但是我無法讓它工作。 touchesBegan()的重載工作正常,它實際上是與pressDelegate?.numpadView(self)的行,它不會調用GameController類中的委託函數。我難以理解什麼是缺少的工作?不被稱爲Swift代表

爲了簡單起見,我清理了代碼以僅留下與問題相關的基本內容。

NumpadView.swift

protocol NumpadPressDelegateProtocol { 
    func numpadView(numpadView: NumpadView) 
} 

class NumpadView: UIButton{ 
    var pressDelegate: NumpadPressDelegateProtocol? 

    init(char: Character) { 
    let frame = CGRectMake(160, 100, 50, 50) 
    super.init(frame:frame) 

    self.setTitle("\(char)", forState: UIControlState.Normal) 
    self.userInteractionEnabled = true 
    } 

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    pressDelegate?.numpadView(self) 
    } 
} 

GameController.swift

class GameController: NumpadPressDelegateProtocol { 

    func numpadView(numpadView: NumpadView) { 
    //do something 
    } 

} 

回答

22

聲明GameControllerNumpadPressDelegateProtocol是不足以讓您獲得回調。您還需要在Gamecontroller內設置NumpadView實例的pressDelegate。假設numpadView是實例變量是它IBOutlet中與否,你必須設置委託像

內GameController初始化

numpadView.pressDelegate = self 
2

你有設置pressDelegate屬性的東西?在你顯示的代碼中沒有分配給它。你在你的代碼中的其他地方分配了什麼?

+0

不,我不知道。我應該分配什麼以及在哪裏? –

+0

您需要創建一個'GameController'對象並將其分配給'pressDelegate'屬性。由於'GameController'被聲明爲符合你的'NumpadPressDelegateProtocol'協議。然後,當你的'touchesBegan'函數執行時,會有'pressDelegate'對象來調用'numpadView()'。 –