我有一个简单的ViewController,中间有一个View,当我添加UITapGestureRecognizer时,它将正常运行,但是当我从外部类尝试相同的操作时,它将不起作用(从未调用该方法)。 我的问题是
我需要对Listener类进行哪些更改以使其调用其中的方法
以下是代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
Listener(view : view , viewController: self).listen()
}
@objc func onNewTabArrived(){
print("Hello from inside the controller")
}
}
class Listener {
let view : UIView
let viewController: UIViewController
init(view : UIView , viewController: UIViewController){
self.view = view
self.viewController = viewController
}
func listen(){
// If you set the target as viewController it will call the method named onNewTabArrived inside it , printing "Hello from inside the controller"
// let tab = UITapGestureRecognizer(target: viewController, action: #selector(onNewTabArrived))
// view.addGestureRecognizer(tab)
// This will not work! the text "Hello from inside Listener" will never be printed, How can I force it to be called ?.
let tab = UITapGestureRecognizer(target: self, action: #selector(onNewTabArrived))
view.addGestureRecognizer(tab)
}
@objc func onNewTabArrived(){
print("Hello from inside Listener")
}
}
答案 0 :(得分:2)
您的Listener
对象在创建后即被释放。尝试将其存储到属性中
@IBOutlet weak var myView: UIView!
var listener: Listener?
override func viewDidLoad() {
super.viewDidLoad()
self.listener = Listener(view : view , viewController: self)
self.listener?.listen()
}