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