Swift 4 add gesture: override vs @objc

2019-06-17 02:31发布

I'm looking to add a gesture to my view as follows:

    override func viewDidLoad() {
    super.viewDidLoad()

    < blah blah blah >

    // Add tap gesture
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    myView.addGestureRecognizer(tap)
}

However, in Swift 4 my compiler is giving me the following error:

Argument of '#selector' refers to instance method 'handleTap()' that is not exposed to Objective-C

The suggestion is to add @objc to expose this instance method to Objective-C.

The other option to implement this (through code only) would be to override the touchesBegan() function and use that to handle the tap.

I am trying to do this the 'Swift' way without having to bring in Obj-C. Is there a pure Swift way to add this tap gesture without using @objc? Or is that the normal and intended way of adding this tap gesture?

1条回答
爷的心禁止访问
2楼-- · 2019-06-17 03:10

Using @objc here is the normal and intended way.

The underlying gesture recogniser code is written in Objective-C so you need to make your selector callable from Objective-C and that is all @objc is doing.

Your alternative technique is still using Objective C-APIs, but interacting with them without selectors so it is just less visible.

查看更多
登录 后发表回答