1

で非常に奇妙な動作が見られUITextFieldます。カスタムキーボードを実装しましたが、iOS 7 以降でうまく機能します。ただし、iOS 6 では、次の行が呼び出されると (「バックスペース」を実行した後)、テキスト フィールドのカーソルが消え、辞任して最初のレスポンダーに戻らない限り編集できず、プレースホルダーと実際のテキストが重なります。

私の「バックスペース」機能に関連するコードは次のとおりです。

//Get the position of the cursor
UITextPosition *selStartPos = self.textBeingEdited.selectedTextRange.start;
int start = (int)[self.textBeingEdited offsetFromPosition:self.textBeingEdited.beginningOfDocument toPosition:selStartPos];

//Make sure the cursor isn't at the front of the document
if (start > 0) {

    //Remove the character before the cursor
    self.textBeingEdited.text = [NSString stringWithFormat:@"%@%@", [self.textBeingEdited.text substringToIndex:start - 1], [self.textBeingEdited.text substringFromIndex:start]];

    //Move the cursor back 1 (by default it'll go to the end of the string for some reason)
    [self.textBeingEdited setSelectedTextRange:[self.textBeingEdited textRangeFromPosition:[self.textBeingEdited positionFromPosition:selStartPos offset:-1] toPosition:[self.textBeingEdited positionFromPosition:selStartPos offset:-1]]];
    //^This line is causing the issue
}

そして、これが私がiOS 6で見ているものです:

奇妙な行動

誰でもこれについて何か洞察がありますか?ありがとう!

編集

これは、 として設定されているゼロ以外の値ごとに発生しているようoffsetです。

4

1 に答える 1

1

編集:完全に新しいソリューション

最後に問題を理解しました。基本的に、私が見てきたことからtext、 a のを置き換えると、文字列の最後UITextFieldにリセットselectedTextRangeされます (カーソルがある場所なので、これは理にかなっています)。これを念頭に置いて、iOS 6 および 7 で動作する次のコードを思いつくことができました。

//Get the position of the cursor
UITextPosition *startPosition = self.textBeingEdited.selectedTextRange.start;
int start = (int)[self.textBeingEdited offsetFromPosition:self.textBeingEdited.beginningOfDocument toPosition:startPosition];

//Make sure the cursor isn't at the front of the document
if (start > 0) {

    //Remove the character before the cursor
    self.textBeingEdited.text = [NSString stringWithFormat:@"%@%@", [self.textBeingEdited.text substringToIndex:(start - 1)], [self.textBeingEdited.text substringFromIndex:start]];
    //Note that this line ^ resets the selected range to just the very end of the string

    //Get the position from the start of the text to the character deleted's index - 1
    UITextPosition *position = [self.textBeingEdited positionFromPosition:self.textBeingEdited.beginningOfDocument offset:(start - 1)];

    //Create a new range with a length of 0
    UITextRange *newRange = [self.textBeingEdited textRangeFromPosition:position toPosition:position];

    //Update the cursor position (selected range with length 0)
    [self.textBeingEdited setSelectedTextRange:newRange];
}

基本的に何が起こっているかというと、削除されたばかりの文字の前の文字から始まる長さのUITextRangefromを作成しています。UITextPosition0

これが同様の問題を抱えている人に役立つことを願っています。私はこのために気が狂っていました!

于 2014-08-20T06:59:53.423 に答える