6

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?

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

4

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 likely replaceRange:withText:. Try swizzling that and performing your call when the text argument is an empty string. Also make sure your swizzling function doesn't return an error.

ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
  • But [`UITextInput`](http://developer.apple.com/library/IOS/#documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITextInput) conforms to [`UIKeyInput`](http://developer.apple.com/library/IOS/documentation/UIKit/Reference/UIKeyInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIKeyInput), which requires `deleteBackward` to be implemented. So, shouldn't that require `UITextField` to implement `deleteBackward`? – ma11hew28 Oct 20 '11 at 17:15
  • Also, in my subclass (and in my category) of `UITextField`, I implemented `replaceRange:withText:` with just an `NSLog` to see if it gets called, and it doesn't. – ma11hew28 Oct 20 '11 at 17:28
  • @Matt Yes, it requires that `deleteBackward` is implemented, but it doesn't necessarily mean it will be used. It was just a possibility. However, rereading your question, I noticed that you are only worried about when it is empty. Does either method get called if its not empty? Maybe the input system doesn't tell the text field about the keypress if it's empty. – ughoavgfhw Oct 20 '11 at 20:55
  • I've played with this a fair bit; neither method gets called when you backspace on an empty textfield. – BJ Homer Oct 21 '11 at 02:36