iOS UITextField changes position when text is changed

拜拜、爱过 提交于 2019-12-07 12:32:28

问题


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?


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/13917949/ios-uitextfield-changes-position-when-text-is-changed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!