UPDATE:
W iOS5 i powyżej jest możliwe, aby to zrobić, ponieważ UITextField i UITextView zgodne z protokołem UITextInput. Proszę spojrzeć na to: "Can I select a specific block of text in a UITextField?" na przykład :).
Nadzieja pomaga
OLD ODPOWIEDŹ: (iOS4.x i poniżej):
Nie ma sposobu, aby to osiągnąć za pomocą API publicznych (nie, że wiem). Jednak znalazłem kilka metod prywatnych (nieudokumentowane metody może dlatego, że nie mają prefiks podkreślenia, że metody prywatne zazwyczaj)
selectionRange
setSelectionRange:
Poniżej pracy Kod grzywny (co najmniej w symulatorze 4.3) i Używam KVC, aby uniknąć irytujących ostrzeżeń. (self
jest instancją podklasy 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"];
}
}
Ponieważ nie są to publiczne API, używać na własne ryzyko, nie wiem, czy będą one przechodzić przegląd Apple.
BTW: znalazłem je za pomocą:
#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])));
}
Very nice. Dziękuję za udostępnienie tego. – DenVog