没有调用Swift代表 [英] Swift Delegate Not Being Called
问题描述
我有一个带有委托的视图,我想在按下按钮时在GameController中调用numpadView(numpadView :),但是我无法使其正常工作. touchesBegan()的重载工作正常,这实际上是与pressDelegate?.numpadView(self)相同的那一行,它不会在GameController类中调用委托函数.我为使它正常工作缺少什么而感到困惑?
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
}
}
推荐答案
将GameController
声明为NumpadPressDelegateProtocol
不足以使您获得回调.您还需要在Gamecontroller
中设置NumpadView
实例的pressDelegate
.假设numpadView
是实例变量(无论是否为IBOutlet),您都必须将委托设置为
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
GameController内部初始化
Inside GameController init
numpadView.pressDelegate = self
这篇关于没有调用Swift代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!