初始化gestureRecognizer时查找目标

时间:2015-01-01 22:27:47

标签: ios swift

我尝试将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,我是不是错了?

1 个答案:

答案 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!)
    }
}