开发者

Move programmatically cursor in UiTextField

I need to tweak UiTextField behavior so that I can programmatically insert some asterisks and move the cursor at the beginning of the string; I tried the "paste" trick (http://dev.ragfield.com/2009/09/insert-te开发者_开发问答xt-at-current-cursor-location.html), but the cursor is moved at the end. The effect I try to achieve is like this: At the start:


then the user insert characters f***** fo**** foo*** etc...

Is this possible or the tweaks I've to do don't deserve the effort?

Thanx

-G-


UPDATE:

In iOS5 and above is possible to do this because UITextField and UITextView conform to UITextInput protocol. Please take a look at this: " Can I select a specific block of text in a UITextField? " for an example :).

Hope it helps


OLD ANSWER: (iOS4.x and below):

There is no way to accomplish this using public APIs (Not that I know). However I have found a couple of private methods: (maybe undocumented methods because they don't have the underscore prefix that private methods usually have)

selectionRange
setSelectionRange:

Below code work fine (at least in the simulator 4.3) and I am using KVC so I can avoid annoying warnings. (self is a instance of a subclass of 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"];
    }
}

Since these are not public APIs, use at your own risk, I don't know if they will pass Apple's review.

BTW: I found them using:

#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])));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜