Clay Smith
Clay Smith

Reputation: 189

UITapGestureRecognizer Error

I have been struggling with this issue for a few hours. I can't seem to understand the procedure of using a UITapGestureRecognizer. Any help would be appreciated.

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    let textInView = "This is my text."
    textView.text = textInView

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapResponse(_:)))
    tapGesture.numberOfTapsRequired = 1
    textView.addGestureRecognizer(tapGesture)

    func tapResponse(sender: UITapGestureRecognizer) {
        var location: CGPoint = sender.location(in: textView)
        location.x = textView.textContainerInset.left
        location.y = textView.textContainerInset.top

        print(location.x)
        print(location.y)
    }
 }

Upvotes: 0

Views: 33

Answers (1)

backslash-f
backslash-f

Reputation: 8193

You have a function (tapResponse) inside a function (viewDidLoad).

Put it outside of viewDidLoad. Then reference it like so:

override func viewDidLoad() {
    super.viewDidLoad() // Remember to always call super.

    let tapGesture = UITapGestureRecognizer(
        target: self,
        action: #selector(ViewController.tapResponse(sender:)) // Referencing.
    )

    tapGesture.numberOfTapsRequired = 1
    textView.addGestureRecognizer(tapGesture)
}

// tapResponse is now outside of viewDidLoad:
func tapResponse(sender: UITapGestureRecognizer) {
    var location: CGPoint = sender.location(in: imageView)
    location.x = textView.textContainerInset.left
    location.y = textView.textContainerInset.top    
    print(location.x)
    print(location.y)
}

Done:

works

Upvotes: 2

Related Questions