IOS UITextField moves when text changes

I use this to center the text box over something appropriate:

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

It looks great, nice, and focused on an object ready to receive text. I would like the text to be generated in a certain way, therefore, in the editor of the modified handler, I revise the text and set the new text:

 [textField setText:newText]; 

When I do this, the text box will move to its previous position before it is centered. I would like the text box to stay centered over the object.

My experience is that probably the best way to do this, i.e. move a text field and dynamically change its contents, without the need to work with various quirks. Any tips?

+4
source share
2 answers

To format a UITextField during editing, you can try 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 kept the UITextfield centered. When he discovers “4” at the beginning, in the center or anywhere, he will replace it with “Hi,” while maintaining the behavior of center alignment.

+2
source

In addition to the code above, the following is used to replace 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]; 

A ghostly decision, for which there should be an easy task!

+1
source

All Articles