UITapGestureRecognizer 错误

Posted

技术标签:

【中文标题】UITapGestureRecognizer 错误【英文标题】:UITapGestureRecognizer Error 【发布时间】:2017-04-21 00:04:03 【问题描述】:

我已经为这个问题苦苦挣扎了几个小时。我似乎无法理解使用 UITapGestureRecognizer 的过程。任何帮助将不胜感激。

@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)
    
 

【问题讨论】:

【参考方案1】:

您在函数 (viewDidLoad) 中有一个函数 (tapResponse)。

把它放在viewDidLoad之外。然后像这样引用它:

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)

完成:

【讨论】:

谢谢!困扰我很久了。

以上是关于UITapGestureRecognizer 错误的主要内容,如果未能解决你的问题,请参考以下文章

UIScrollView 上的错误 UITapGestureRecognizer

在将 UITapGestureRecognizer 添加到 UIImageView 时进行错误访问

UITapGestureRecognizer 导致崩溃并显示不同的错误消息

UITapGestureRecognizer 被识别为 UILongPressGestureRecognizer

Swift - 无法识别的选择器到实例 - UITapGestureRecognizer

UITapGestureRecognizer 在多次点击时崩溃