Swift代表没有被调用

Jer*_*Rea 13 uikit ios swift

我有一个代表的视图,我希望在按下按钮时在GameController中调用numpadView(numpadView :),但是我无法让它工作.touchesBegan()的重载工作正常,它实际上是使用pressDelegate?.numpadView(self)的行,它不会调用GameController类中的委托函数.为了让它起作用,我很遗憾失去了什么?

为了简单起见,我清理了代码,只留下与问题相关的基本内容.

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)
  } 
}
Run Code Online (Sandbox Code Playgroud)

GameController.swift

class GameController: NumpadPressDelegateProtocol {

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

}
Run Code Online (Sandbox Code Playgroud)

rak*_*hbs 29

声明GameController作为NumpadPressDelegateProtocol是不够的,你得到一个回调.您还需要设置pressDelegate的的 NumpadView内部实例 Gamecontroller.假设numpadView实例变量是IBOutlet,你必须设置委托

在GameController内部初始化

 numpadView.pressDelegate = self
Run Code Online (Sandbox Code Playgroud)