Search code examples
iosios8textdocumentproxy

iOS 8 textDocumentProxy - able to delete more than one space?


I would like to delete multiple spaces from self.textDocumentProxy when working with my extension's KeyboardViewController, and was wondering if there is a Apple-supported method that specifically performs this action?

So far, I have been using a pretty "hacky" way of doing the following (here it deletes all the previous characters found on textDocumentProxy):

for (int i = 0; i < self.textDocumentProxy.documentContextBeforeInput.length; i++){
        [self.textDocumentProxy deleteBackward];
    }

The issue with this lies in the method deleteBackward, which, depending on what prompt is given, always deletes around half (its quite reliable, especially when documentContextBeforeInput is longer than 20 characters) of the total number of times its told to delete. Since this is rather unreliable, I was wondering if there is a way to easily delete multiple spaces, or all of the texted in textDocumentProxy.documentContextBeforeInput

Thanks!


Solution

  • There is a fundamental issue in the loop you're using:

    for (int i = 0; i < self.textDocumentProxy.documentContextBeforeInput.length; i++){
        [self.textDocumentProxy deleteBackward];
    }
    

    The i < self.textDocumentProxy.documentContextBeforeInput.length check is performed multiple times. And the .length attribute is actually decreasing by 1 for every deleteBackward you do. i however is merrily increasing by 1 for each iteration.

    As a result only half will be deleted.

    You can flip the order around to fix the issue.

    for (int i = self.textDocumentProxy.documentContextBeforeInput.length; i > 0; i--){
        [self.textDocumentProxy deleteBackward];
    }
    

    You can also cache the original length of the textDocument before you start changing it.