我尝试将UIGestureRecognizer
的子类初始化为类ViewController
的属性,但我不确定将什么作为手势识别器的目标。
class ViewController: UIViewController {
// Not sure where this declaration should happen
var menuGesture: MenuGestureRecognizer = MenuGestureRecognizer(target: self(), action: Selector("menuGestureHandler:"))
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(menuGesture)
}
}
XCode建议self()
,但后来我收到错误:
Swift Compiler Error: Missing argument for parameter #1 in call`
在我看来它失败了,因为我试图在类范围内声明变量。如果是这种情况,我应该在哪里/如何宣布手势识别器?
我非常精通Objective-C但最近改用了Swift,我是不是错了?
答案 0 :(得分:0)
只需在viewDidLoad
中声明:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let menuGesture = MenuGestureRecognizer(target: self, action: "menuGestureHandler:")
self.view.addGestureRecognizer(menuGesture)
}
}
如果您希望menuGesture
成为ViewController
的媒体资源,请将其设为可选项并在viewDidLoad
中指定:
class ViewController: UIViewController {
var menuGesture: MenuGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
menuGesture = MenuGestureRecognizer(target: self, action: "menuGestureHandler:")
self.view.addGestureRecognizer(menuGesture!)
}
}