daspianist
daspianist

Reputation: 5515

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!

Upvotes: 1

Views: 1914

Answers (3)

RomOne
RomOne

Reputation: 2105

Maybe try this solution that will erase everything in the input text, not only the text before the cursor ;)

func deleteInputText() {

    if let afterInput = self.textDocumentProxy.documentContextAfterInput {
        self.textDocumentProxy.adjustTextPositionByCharacterOffset(afterInput.characters.count)
    }
    while let _=self.textDocumentProxy.documentContextBeforeInput {

            self.textDocumentProxy.deleteBackward()


    }

}

Upvotes: 0

EWit
EWit

Reputation: 1994

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.

Upvotes: 1

Rabiea
Rabiea

Reputation: 31

while (self.textDocumentProxy.hasText==YES)
{    
  [self.textDocumentProxy deleteBackward];      
}

should remove all the text.

[self.textDocumentProxy deleteBackward]; deletes only 1 character.

Upvotes: -1

Related Questions