3

I use this to center a text field over something relevant:

[textField setCenter:[someObject center]];
[textField becomeFirstResponder];

This looks great, nice and centered over the object, ready to accept text. I'd like the text formated a certain way, so in the editing changed handler, I revise the text and set to the new text:

[textField setText:newText];

When I do this, the text field will jump to its the old position, from before it was centered. I'd like the text field to stay centered over the object.

My experience is that there is likely a better way to do this, i.e. move the text field and dynamically change its contents, without have to work around various quirks. Any advice?

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48

2 Answers2

2

For Formatting the UITextField while editing you can try out the following code.

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if([string isEqualToString:@"4"]){
        UITextRange *range=textField.selectedTextRange;
        [textField replaceRange:range withText:@"Hi"];
        return NO;
    }
    return YES;
}

I have kept UITextfield with centre alignment. When it detects "4" at the start,centre or any where, it will replace it with "Hi",while maintaining it's centre align behaviour.

NNikN
  • 3,720
  • 6
  • 44
  • 86
  • Confirmed using setText: it still shifts the text field. It might work with replaceRange, but I need to change the text completely, not just replace the range. Looking into it more, it seems unbelievably difficult: no easy way to create UITextRange comprising the entire string, need to subclass two classes UITextRange and UITextPosition, the textField needs to be the first responder. Even after I do all this, I still don't know if the text field will shift. – Yimin Rong Dec 17 '12 at 22:30
0

In addition to the code above, used the following to replace the existing text:

UITextPosition *p0 = [textField beginningOfDocument];
UITextPosition *p1 = [textField positionFromPosition:p0 offset:[[textField text] length]];
UITextRange *complete = [textField textRangeFromPosition:p0 toPosition:p1];
[textField replaceRange:complete withText:newText];

Ghastly solution for what should be an easy task!

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48