[英]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. 我有一个具有委托的视图,我想在按下按钮时在GameController中调用numpadView(numpadView :),但是我无法使其正常工作。 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.
touchesBegan()的重载工作正常,这实际上是与pressDelegate?.numpadView(self)相同的那一行,它不会在GameController类中调用委托函数。 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 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 GameController.swift
class GameController: NumpadPressDelegateProtocol {
func numpadView(numpadView: NumpadView) {
//do something
}
}
Declaring GameController
as NumpadPressDelegateProtocol
is not enough for you to get a callback. GameController
将NumpadPressDelegateProtocol
声明为NumpadPressDelegateProtocol
不足以使您获得回调。 You also need to set the pressDelegate
of the NumpadView
instance inside the Gamecontroller
. 您还需要在
pressDelegate
中设置NumpadView
实例的Gamecontroller
。 Assuming numpadView
is the instance variable be it IBOutlet or not, you have to set the delegate like 假设
numpadView
是实例变量(无论是否为IBOutlet),您都必须将委托设置为
Inside GameController init 在GameController内部初始化
numpadView.pressDelegate = self
Have you set the pressDelegate
property to something? 您是否将
pressDelegate
属性设置为某些值? Nothing is assigned to it in the code you've shown. 您显示的代码中未分配任何内容。 Do you assign something to it elsewhere in your code?
您是否在代码的其他位置为其分配了某些内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.