将 UITextView 光标位置设置为文本结尾 [英] Setting UITextView cursor position to end of text

查看:26
本文介绍了将 UITextView 光标位置设置为文本结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整个上午都在寻找解决方案,但还没有找到有效的方法.

I've looked for a solution to this all morning, but have yet to find something that works.

我有一个文本视图,其中包含一些我不希望用户能够修改的现有固定文本.在这种情况下,我的每个文本视图都以1."、2."等开头.他们输入的文本将被编号以用于我稍后要做的事情.

I have a text view that has some existing fixed text in it that I don't want the user to be able to modify. In this case, each of my text views start with "1. ", "2. ", etc. The idea being that the text they entered will be numbered for something I'm doing later.

我不希望用户能够删除此文本(它本质上是永久的").我也不想让他们开始在这个前置文本中间添加文本.

I don't want the user to be able to delete this text (it is essentially "permanent"). I also don't want to allow them to start adding text in the middle of this pre-text.

为了解决这个问题,我做了:

To handle this, I have done:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    if (range.location < 3) return NO;

    return YES;
}

这很好用,除了如果用户触摸我的1."、2."等部分视图中的任何位置,它会将光标设置在那里,然后阻止用户输入文本,因为范围位置检查.在这种情况下,我想要做的是将光标(可能在 textViewDidBeginEditing 中)设置到视图中文本的末尾.但是,无论我使用什么 selectedRange 组合,我都无法让该死的光标移动到最后.任何帮助将不胜感激.

This works great, except that if the user touches anywhere in my "1. ", "2. ", etc. parts of the view, it will set the cursor there, which then prevents the user from typing text because of the range location check. What I want to do in this case is set the cursor (perhaps in textViewDidBeginEditing) to the end of the text in the view. However, regardless of what combination of selectedRange I use, I just can't get the darn cursor to move to the end. Any help would be greatly appreciated.

推荐答案

您可以考虑注册到 UIKeyboardWillShowNotification 并在收到通知后,将 textview 的 userInteractionEnabled 设置为 <代码>否.

You could consider registering to the UIKeyboardWillShowNotification and upon receiving the notification, set the textview's userInteractionEnabled to NO.

此外,以一种方式实现 shouldChangeTextInRange 方法,如果 replacementText 等于字符串 @"",则您不会更改文本(@"" 表示用户正在敲击退格键).当用户完成文本编辑后恢复用户交互.

Also, implement the shouldChangeTextInRange method in a way that if replacementText is equal to the string @"" you don't change the text (@"" meaning the user is tapping backspace). Restore user interaction when the user finishes editing the text and there you go.

祝你好运!

这篇关于将 UITextView 光标位置设置为文本结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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