Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UITextField changes position when text is changed

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?

like image 964
Yimin Rong Avatar asked Jan 22 '26 11:01

Yimin Rong


1 Answers

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.

like image 150
NNikN Avatar answered Jan 24 '26 03:01

NNikN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!