テキスト フィールドの UITextRange オブジェクトを介して UITextField の現在のキャレット位置に到達する方法はありますか? UITextField によって返される UITextRange は何の役にも立ちませんか? UITextPosition のパブリック インターフェイスには、可視メンバーはありません。
13714 次
2 に答える
20
私は昨夜同じ問題に直面していました。UITextField で offsetFromPosition を使用して、選択した範囲の「開始」の相対位置を取得し、位置を計算する必要があることがわかりました。
例えば
// Get the selected text range
UITextRange *selectedRange = [self selectedTextRange];
//Calculate the existing position, relative to the beginning of the field
int pos = [self offsetFromPosition:self.beginningOfDocument
toPosition:selectedRange.start];
テキストフィールドを変更した後、ユーザーの位置を復元する方が簡単だったので、 endOfDocument を使用することになりました。私はそれについてここにブログ投稿を書きました:
http://neofight.wordpress.com/2012/04/01/finding-the-cursor-position-in-a-uitextfield/
于 2012-04-01T17:07:18.420 に答える
13
uitextfield でカテゴリを使用し、setSelectedRange と selectedRange を実装しました (uitextview クラスに実装されたメソッドと同様)。例は B2Cloud hereにあります。コードは以下のとおりです。
@interface UITextField (Selection)
- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;
@end
@implementation UITextField (Selection)
- (NSRange) selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void) setSelectedRange:(NSRange) range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
于 2012-12-04T13:11:49.430 に答える