【问题标题】:Swift 3: unrecognized selector sent to instance for gesture recognizerSwift 3:将无法识别的选择器发送到手势识别器实例
【发布时间】:2017-02-21 21:42:13
【问题描述】:

无论我做什么,我总是得到这个错误。

这是在我的cellForItemAtIndexPath 函数中:

cell.postCell.profileImage.userView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "pressedUserImage:"))

以及动作方法:

func pressedUserImage(userView: UIImageView) {
    print(userView.superview) // error happens here.

当然,我的 userView 位于深层视图层次结构中,但它仍然必须工作。由于某种原因,它没有。即使我这样做userImage.superview?.superview 等等,我仍然会收到错误消息。 我尝试改用#selector(pressedUserImage(_:),但没有运气。试过Selector("pressedUserImage:")。没有。

我哪里错了?

更新,这里是cellForItemAtIndexPath 函数:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! Posts
    cell.postCell.profileImage.userView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "pressedUserImage:"))
    cell.postCell.buttonView.sharePost.addTarget(self, action: #selector(pressedShareButton), for: .touchUpInside)

    return cell
}

postCell 基本上是一个包含图像、名称、文本的UIView

这是错误:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[project.PostspressedUserImage]:无法识别的选择器发送到实例 0x7a9a65e0”

【问题讨论】:

  • 可以分享cellForItemAtIndexPath函数吗?
  • 能否也显示确切的异常消息文本
  • 手势识别器处理程序的参数是手势识别器,没有被触摸的视图。在发送者上使用 .view 来获取发送视图。
  • 很抱歉,都在那里。
  • @vacawama,你是什么意思? UITapGestureRecognizer 是手势识别器,不是吗?

标签: ios uicollectionview uitapgesturerecognizer


【解决方案1】:

看来问题出在您的函数签名上。它需要接受手势识别器作为参数,而不是包含视图。

喜欢:

func pressedUserImage(_ sender: UITapGestureRecognizer) { ... }

【讨论】:

  • 然后你可以得到这样的视图:if let userView = sender.view as? UIImageView { // use userView }
  • !!!!!!现在我得去家得宝买干墙水泥。多谢你们!它奏效了。
【解决方案2】:

正如 Joshua 指出的那样,您的函数签名是错误的。您需要正确设置参数的类型,并添加下划线以使参数不命名。

除了他的更改之外,如果您的类不是 Objective-C 类,您还应该将该函数标记为 Objective-C:

@objc func pressedUserImage(_ sender: UITapGestureRecognizer) { ... }

【讨论】:

  • 我猜我把它和 UIButtons 搞混了!
  • “如果你的类不是 Objective-C 类,你也应该将函数标记为 Objective-C”。为什么? Objective-c 的问题在哪里?
  • 选择器是一个 Objective-C 结构。为了使运行时能够使用选择器访问函数,它必须使用 Objective-C 样式的调度。
  • 请注意,对于按钮和手势识别器上的选择器来说,这很少会成为问题,因为通常的目标是 UIViewController,它是一个 Objective-C 类。
猜你喜欢
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多