2013-05-08 25 views
15

UITextFieldのカーソル位置を制御しようとしています。ユーザーは、一度に複数の文字をテキストフィールドの中央に挿入することはできません。これをテキストフィールドの最後に移動します。だからSOのこの投稿:Control cursor position in UITextFieldそれは私の問題を解決します。しかし、私は現在のカーソルの位置を知る必要があります。UITextFieldのカーソル位置を取得する

私のコードは次のようになります。それは私のIDXにエラーを与えている

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    if (textField.tag == 201) 
    { 
    [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)]; 
    } 
} 

。それをどうやって見つけるのですか?

答えて

27

UITextFieldは、現在の選択を取得する方法を持つUITextInputプロトコルに準拠しています。しかし、その方法は複雑です。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    if (textField.tag == 201) { 
     UITextRange *selRange = textField.selectedTextRange; 
     UITextPosition *selStartPos = selRange.start; 
     NSInteger idx = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selStartPos]; 

     [myclass selectTextForInput:textField atRange:NSMakeRange(idx, 0)]; 
    } 
} 
+2

次に、uitextfield内の文字を削除した後にカーソルが同じ場所に残るようにするにはどうすればよいですか? – lakesh

3

投稿したコードは、カーソルの位置を特定するためには機能しません。セットではなくgetメソッドが必要です。これは、の線に沿って何かする必要があります。詳細については

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    if (textField.tag == 201) 
    { 
     UITextRange selectedRange = [textField selectedTextRange]; 
     // here you will have to check whether the user has actually selected something 
     if (selectedRange.empty) { 
       // Cursor is at selectedRange.start 
       ... 
     } else { 
       // You have not specified home to handle the situation where the user has selected some text, but you can use the selected range and the textField selectionAffinity to assume cursor is on the left edge of the selected range or the other 
       ... 
     } 
    } 
} 

- UITextInputプロトコルにチェックhttp://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITextInput

更新:@rmaddyは私の応答で、私は逃したいくつかの良い余分なビットを掲載している - テキストを処理する方法位置をNSTextRangeから取得し、NSTextPositionをintに変換します。

+0

次に、uitextfield内の文字を削除した後でカーソルが同じ場所に残っていることを確認します。 – lakesh

+0

これは保証できません。最初に文字を削除するには、フィールドの内容全体を設定する必要があります。必然的にカーソルが最後まで移動します。あなたはあなたが好きな位置にそれを戻さなければなりません。 –

4

スウィフトバージョン

if let selectedRange = textField.selectedTextRange { 

    let cursorPosition = textField.offsetFromPosition(textField.beginningOfDocument, toPosition: selectedRange.start) 
    print("\(cursorPosition)") 
} 

カーソル位置を取得および設定についての私の完全な答えはhereです:あなたはこのようなものが必要。

関連する問題