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

编辑:全新的解决方案

终于弄清楚了问题所在。基本上,据我所见,当您替换textaUITextField时,它会将 a 重置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];
}

从本质上讲,它正在创建一个UITextRange从刚刚删除的字符之前的字符开始的UITextPosition长度为的字符。0

希望这可以帮助有类似问题的人,因为这个我疯了!

于 2014-08-20T06:59:53.423 回答