Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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-text-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-

like image 511
Giordano Scalzo Avatar asked Jun 30 '10 14:06

Giordano Scalzo


1 Answers

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])));
}
like image 169
nacho4d Avatar answered Sep 22 '22 04:09

nacho4d