views:

472

answers:

2

I have a text field that is always of the format "XX0000000XX", X being a letter, 0 being a number. I switch keyboards as the user is typing depending on whether they need to enter a number or letter.

This works fine, until the user positions the cursor in the middle of the text field to make an edit. How do I determine the cursor position within a UITextField?

I know a UITextView has a selectedRange that can be used, but I've read that you can't force a UITextView to be single line entry? i.e. Disable multiple lines of text.

+1  A: 

Hey Tim,

Clever bit with the keyboards. My immediate thought is that perhaps that you shouldn't allow the user to move the cursor in the first place.

This isn't without precedent in the iPhone UI. The telephone keypad view, for example, restricts the user to sequential input. I have also found this technique useful for currency input. Anywhere with input that has a very rigid syntax, basically, seems like a candidate for this kind of treatment. Might work well for your situation.

Not sure if this is the best method, but here's how I do it:

A UITextField to capture input and a UILabel to display the input. The text field is hidden but is sent becomeFirstResponder to trigger the keyboard. As the user types, delegate methods do their thing to format the text, if necessary (as with currency), and update the UILabel, which provides the user feedback on their input.

Depending upon the situation, you may wish to style the UILabel in such a way that makes it clear the user can't use it as they would a selectable text field while reassuring them that it is, in fact, their input.

With 11 characters in play, I can see how curser editing might be useful. Still, phone numbers are often in that same range and I never have a problem with the sequential editor in the Phone app.

Danilo Campos
A: 

There's a UITextDelegate method -textField:shouldChangeCharactersInRange:replacementString: which should be all you need to do what you describe. Implement it to enforce whatever formatting rules you want. You shouldn't care where the cursor is, just the range of the change that's proposed.

NSResponder