gpt4 book ai didi

iphone - 以编程方式在 UiTextField 中移动光标

转载 作者:行者123 更新时间:2023-12-03 18:56:15 25 4
gpt4 key购买 nike

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

<小时/>

然后用户插入字符F*****佛****富***等等...

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

谢谢

-G-

最佳答案

更新:

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

希望对你有帮助

<小时/>

旧答案:(iOS4.x 及更低版本):

使用公共(public) API 无法实现此目的(据我所知)。但是我发现了一些私有(private)方法:(可能是未记录的方法,因为它们没有私有(private)方法通常具有的下划线前缀)

selectionRange
setSelectionRange:

下面的代码工作正常(至少在模拟器 4.3 中),并且我使用 KVC,这样我就可以避免恼人的警告。 (selfUITextField 子类的实例)

- (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"];
}
}

由于这些不是公共(public)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])));
}

关于iphone - 以编程方式在 UiTextField 中移动光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3150038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com