views:

326

answers:

2

Hi,

I'm creating an application on the iPad. I create a custom keyboard using UITextField's inputView property. To insert text at the cursor position, I use the copy & paste method (http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html), which works fine. Now, I want to create the delete key. The code that I'm using is:

if (textField.text.length > 0) {
    textField.text = [textField.text substringToIndex:textField.text.length-1];
}

However, as you may know, it only deletes the last character no matter where the cursor is. Does anyone know a better solution?

Thank you very much!

+1  A: 

Consider switching to a UITextView, which has a selectedRange property for getting the currently selected range of characters or the cursor location if nothing is selected. Unfortunately, UITextField does not have this method, and I have not found another way to find the cursor location.

The documentation for the selectedRange property can be found here here on Apple's website. It consists of an NSRange in which selectedRange.location is the cursor location and selectedRange.length is the number of selected characters (or zero if nothing is selected.) Your code will have to look something like this:

textView.text = [textView.text stringByReplacingCharactersInRange:textView.selectedRange withString:@""];
Tom S
Hi Tom. Thank you very much. However, I'm using the UITextField in UISearchBar and I don't think I can change it to UITextView. Anyway, I will try implementing my own search bar using UITextView. Thank you again.
Midori
A: 

A UITextView has a selectedRange property. Given that you could build a range to use with the following code:

textView.text = [textView.text stringByReplacingCharactersInRange:?? withString:@""];

A UITextField has no such range property. Obviously it has a _selectionRange member but that is private.

I think your choices are either to switch to a UITextView or prevent having the cursor anywhere but at the end of the text and using your current code.

You can always submit a bug report to Apple requesting that they document selectedRange for UITextField, or ask for special permission to access the field directly.

drawnonward
Thank you very much. However, a problem is that I'm using UISearchBar and it only contains a UITextField. I may implement my own search bar using UITextView, but there are some features that I miss in the Apple's seach bar, such as the scope filter and the appearance of the textfield (i.e. very rounded corners.) Anyway, thank you very much. I will try your suggestions. I never known that we can ask for permission to use private APIs.
Midori
You could try textView.layer.cornerRadius for the rounded corners. It would take some work, but you may be able to place a text view directly over the search bar, so the text view has focus but is otherwise clear and it looks like the search bar has focus.
drawnonward