iOS UITextField 更改文本时更改位置 [英] iOS UITextField changes position when text is changed

查看:23
本文介绍了iOS UITextField 更改文本时更改位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用它来将文本字段置于相关内容的中心:

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?

推荐答案

对于在编辑时格式化 UITextField,您可以尝试以下代码.

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;
}

我保持 UITextfield 居中对齐.当它在开始、中心或任何地方检测到4"时,它将用Hi"替换它,同时保持它的中心对齐行为.

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.

这篇关于iOS UITextField 更改文本时更改位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆