我正在尝试使用点击手势识别器来在点击图像时打开URL。
代码构建成功,但是当我尝试点击图像时,它终止并显示
以NSException(lldb)类型的未捕获异常终止
在控制台中。控制台也会显示
[Hello.ViewController clickToOpen]:无法识别的选择器已发送到实例。
还有一个
线程1:信号SIGABRT
在行中
AppDelegate.swift中的类AppDelegate:UIResponder,UIApplicationDelegate {“。
ViewController代码如下:
//
// 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)
}
}
}
最佳答案
替换您的点击手势代码,然后从Swift 3.x开始使用#selector
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(clickToOpen))
self.view.addGestureRecognizer(tapGesture)