【问题标题】:Move programmatically cursor in UiTextField在 UiTextField 中以编程方式移动光标
【发布时间】:2011-03-10 04:00:02
【问题描述】:

我需要调整 UiTextField 的行为,以便我可以以编程方式插入一些星号并将光标移动到字符串的开头; 我尝试了“粘贴”技巧(http://dev.ragfield.com/2009/09/insert-text-at-current-cursor-location.html),但光标在末尾移动。 我尝试达到的效果是这样的: 开头:


然后用户插入字符 F***** *** 呸*** 等等……

这是可能的还是我要做的调整不值得付出努力?

感谢

-G-

【问题讨论】:

    标签: iphone cocoa-touch uitextfield


    【解决方案1】:

    更新:

    在 iOS5 及更高版本中可以这样做,因为 UITextField 和 UITextView 符合UITextInput 协议。请看一下:“Can I select a specific block of text in a UITextField?”作为示例:)。

    希望对你有帮助


    旧答案:(iOS4.x 及以下):

    没有办法使用公共 API 来实现这一点(我不知道)。 但是我发现了几个私有方法:(可能是未记录的方法,因为它们没有私有方法通常具有的下划线前缀)

    selectionRange
    setSelectionRange:
    

    下面的代码工作正常(至少在模拟器 4.3 中),我正在使用 KVC,所以我可以避免恼人的警告。 (self 是UITextField 的子类的一个实例)

    - (void) moveToRight{
    
        NSRange selectedRange = [[self valueForKey:@"selectionRange"] rangeValue];
        if (selectedRange.location != NSNotFound) {
            if (selectedRange.length > 0) {
                selectedRange.location = NSMaxRange(selectedRange);
                selectedRange.length = 0;
            }else if (selectedRange.location < self.text.length) {
                selectedRange.location += 1;
            }
            [self setValue:[NSValue valueWithRange:selectedRange] forKey:@"selectionRange"];
        }
    }
    - (void) moveToLeft{
    
        NSRange selectedRange = [[self valueForKey:@"selectionRange"] rangeValue];
        if (selectedRange.location != NSNotFound) {
            if (selectedRange.length > 0) {
                selectedRange.length = 0;
            }else if (selectedRange.location > 0) {
                selectedRange.location -= 1;
            }
            [self setValue:[NSValue valueWithRange:selectedRange] forKey:@"selectionRange"];
        }
    }
    

    由于这些不是公共 API,使用风险自负,我不知道它们是否会通过 Apple 的审核。

    顺便说一句: 我发现他们使用:

    #import "/usr/include/objc/objc-runtime.h"
    
    unsigned int methodCount = 0;
    Method *mlist = class_copyMethodList([UITextField class], &methodCount);
    for (int i = 0; i < methodCount; ++i){
        NSLog(@"%@", NSStringFromSelector(method_getName(mlist[i])));
    }
    

    【讨论】:

    • 非常好。感谢分享。
    猜你喜欢
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多