初始化 gestureRecognizer 时查找目标
Finding Target when initializing gestureRecognizer
我正在尝试将 UIGestureRecognizer
的子 class 初始化为 class 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`
在我看来它失败了,因为我试图在 class 范围内声明变量。如果是这样,where/how 我应该声明手势识别器吗?
我非常精通 Objective-C 但最近转向了 Swift,我是不是做错了?
只需在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!)
}
}
我正在尝试将 UIGestureRecognizer
的子 class 初始化为 class 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`
在我看来它失败了,因为我试图在 class 范围内声明变量。如果是这样,where/how 我应该声明手势识别器吗?
我非常精通 Objective-C 但最近转向了 Swift,我是不是做错了?
只需在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!)
}
}