0

正如标题所说,我收到此错误消息:

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每次都创建的解决方案。

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

4

1 回答 1

0

如果您要分享 FULL 错误消息,您应该:

-[TheClass tapAction:] unrecognized selector sent to instance

whereTheClass应该是调用的实例的类tapInside(target:action:)

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

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

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

所以:

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)->())?) {...}
于 2021-09-15T10:10:56.620 回答