I am trying to use a tap gesture recognizer to open an URL when tapping an image. The code builds successfully but when I try to tap the image, it terminates and displays
terminating with uncaught exception of type NSException (lldb)
in console. Console also displays
[Hello.ViewController clickToOpen]: unrecognized selector sent to instance.
And there is a
Thread 1: signal SIGABRT
in the line
class AppDelegate: UIResponder, UIApplicationDelegate {" in AppDelegate.swift.
The ViewController code is below:
//
// ViewController.swift
// Hello
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
//MARK: Outlets
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var helloName: UILabel!
@IBOutlet weak var imageToTap: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector(("clickToOpen")))
self.imageToTap.addGestureRecognizer(tapGestureRecognizer)
self.imageToTap.isUserInteractionEnabled = true
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
helloName.text = "Hello \(textField.text!)"
textField.text = ""
}
//MARK: Actions
@IBAction func clearButton(_ sender: UIButton) {
helloName.text = "Hello"
}
@IBAction func enterButton(_ sender: UIButton) {
nameTextField.resignFirstResponder()
}
@IBAction func clickToOpen(_ sender: UITapGestureRecognizer) {
if let url = NSURL(string: "http://www.google.com/") {
UIApplication.shared.openURL(url as URL)
}
}
}
Replace your tap gesture code & From swift 3.x you need to use #selector
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(clickToOpen))
self.view.addGestureRecognizer(tapGesture)