阻止用户在UITextField上设置光标位置 [英] Prevent user from setting cursor position on UITextField

查看:421
本文介绍了阻止用户在UITextField上设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用故事板构建的UITextField。我想不允许用户更改光标的位置,并将其始终保留在文本末尾的文本字段中。

I have an UITextField constructed using the storyboard. I want to not allow the user to change the position of the cursor and keep it always at the end of the text into the text field.

我试图改变位置触摸事件中光标的位置,但是当选择文本字段然后再次触摸文本字段来更改光标位置时,位置会发生变化:

I tried to change the position of the cursor at the touchdown event, but when selecting the text field and then change the position of the cursor by touching the text field again, the position is changed:

- (IBAction)amountBoxTouchDown:(id)sender {
    UITextPosition *start = [amountBox positionFromPosition:[amountBox beginningOfDocument] offset:amountBox.text.length];
    UITextPosition *end = [amountBox positionFromPosition:start
                                                   offset:0];
    [amountBox setSelectedTextRange:[amountBox textRangeFromPosition:start toPosition:end]];
}

有谁知道解决方案?谢谢

Does anyone know a solution? Thanks

推荐答案

好的,你要做的就是有一个隐藏的UITextField。

Ok, what you have to do is have a UITextField that is hidden.

将该隐藏文本字段添加到视图中,并在其上调用becomeFirstResponder。从 amountBoxTouchDown:方法。

Add that hidden text field to the view, and call becomeFirstResponder on it. From your amountBoxTouchDown: method.

在Textfield委托中,获取用户输入的文本并将其添加到 amountBox.text 。同时关闭可见amountBox textField的 userInteractionEnabled

In the Textfield delegate, take the text the user typed in and add it to amountBox.text. Also turn off userInteractionEnabled for the visible amountBox textField.

这会产生你想要的效果。

This creates the effect you desire.

查看一些示例代码链接

这篇关于阻止用户在UITextField上设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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