【问题标题】:Swift Customized UIButton unrecognized selector sent to instanceSwift Customized UIButton 无法识别的选择器发送到实例
【发布时间】:2021-11-10 09:57:12
【问题描述】:

正如标题所说,我收到了以下错误消息:

libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[{Project}.{UIView} tapAction:]: unrecognized selector sent to instance 0x156406c70'
terminating with uncaught exception of type NSException

当我尝试像这样自定义UIButton 时:

class BaseButton: UIButton {
    
    private var action: ((UIButton)->())?

    public func tapInside(target: Any?, action: ((UIButton)->())?) {
        self.action = action
        self.addTarget(target, action: #selector(tapAction(_:)), for: .touchUpInside)
    }

    @objc private func tapAction(_ sender: UIButton) {
        if let _f = action {
            _f(self)
        }
    }
    
}

我知道我在不了解基础知识的情况下尝试一些高级的东西。

如果有任何其他解决方案我不必每次都创建tapAction,请告诉我。

更新: 详细信息已添加到错误消息中。

【问题讨论】:

  • 完整的错误信息?但target 不是addTarget() 中的self,因为稍后您会使用action 闭包重定向...

标签: swift uibutton selector addtarget


【解决方案1】:

如果您要分享完整的错误消息,您应该:

-[TheClass tapAction:] unrecognized selector sent to instance

其中TheClass 应该是调用tapInside(target:action:) 的实例的类。

这可能会给你关于你的问题的提示。

即,TheClass 正在调用自己的方法tapAction(_:),这是不知道的。 就像写theClass.tapAction(someSender),这应该不会编译吧?

问题在于,在addTarget(_:action:for:) 中,target 是实现action(选择器)的那个。在这种情况下,它是 selfBaseButton 实例。

所以:

self.addTarget(target, action: #selector(tapAction(_:)), for: .touchUpInside)

=>

self.addTarget(self, action: #selector(tapAction(_:)), for: .touchUpInside)

现在,由于您不再需要 target 参数,您可以将其从方法中删除:

public func tapInside(target: Any?, action: ((UIButton)->())?) {...}

=>

public func tapInside(action: ((UIButton)->())?) {...}

【讨论】:

  • 非常感谢。实际上,我没有意识到 selector 应该在 target 内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
相关资源
最近更新 更多