简体   繁体   中英

Swift Delegate Not Being Called

I have a view with a delegate that I want to have call numpadView(numpadView:) in GameController upon button press, however I can't get it to work. The overload of touchesBegan() works fine, it's really the line with pressDelegate?.numpadView(self) which doesn't call the delegate function in the GameController class. I'm stumped as to what's missing to get it to work?

I cleaned the code to leave only the essential related to the problem for simplicity.

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
  }

}

Declaring GameController as NumpadPressDelegateProtocol is not enough for you to get a callback. You also need to set the pressDelegate of the NumpadView instance inside the Gamecontroller . Assuming numpadView is the instance variable be it IBOutlet or not, you have to set the delegate like

Inside GameController init

 numpadView.pressDelegate = self

Have you set the pressDelegate property to something? Nothing is assigned to it in the code you've shown. Do you assign something to it elsewhere in your code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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