Objective-C 运行时:混合方法名称?
尝试检测 UITextField 中的退格, 我尝试过子类化 UITextField
并覆盖 -[UIKeyInput deleteBackward]
,但它永远不会被调用。因此,我怀疑 UITextField
将 deleteBackward
调配为另一个方法名称。
使用 Objective-C 运行时,如何确定 deleteBackward
已被 swizzled 为哪个方法名称?然后,如何更改实现,以便 UITextField
在当它为空时按下删除键。
另外,这种元编程会让我的应用程序被 App Store 拒绝吗?
In an attempt to Detect backspace in UITextField,
I've tried subclassing UITextField
and overriding -[UIKeyInput deleteBackward]
, but it never gets called. So, I'm suspecting UITextField
swizzles deleteBackward
to another method name.
Using the Objective-C Runtime, how can I determine which method name deleteBackward
has been swizzled to? Then, how can I change the implementation so that UITextField
will call [self.delegate textField:self shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]
when the delete key is pressed when it's empty.
Also, will this kind of metaprogramming get my app rejected from the App Store?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Swizzling 不会更改方法的名称。如果是这样,则无法调用该方法,因为运行时使用该名称查找实现。它所做的只是更改调用特定方法时运行的代码的地址。
我猜测为什么
deleteBackward
方法没有被调用,因为输入系统正在使用更复杂的 UITextInput 协议代替,最有可能的是replaceRange:withText:
。尝试调整它并在text
参数为空字符串时执行调用。还要确保您的 swizzling 函数不会返回错误。Swizzling doesn't change the name of a method. If it did, it would be impossible to call the method, since the runtime finds the implementation using the name. All it does is change the address of the code which is run when you call a specific method.
My guess as to why the
deleteBackward
method isn't being called is that the input system is using a method from the more complicated UITextInput protocol instead, most likelyreplaceRange:withText:
. Try swizzling that and performing your call when thetext
argument is an empty string. Also make sure your swizzling function doesn't return an error.