在iOS 6上使用setSelectedTextRange时的奇怪行为

时间:2014-08-20 06:12:47

标签: ios objective-c ios6 uitextfield uitextposition

我在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上看到的内容:

Strange behavior

任何人对此都有任何见解?谢谢!

修改

对于设置为offset的每个非零值,似乎都会发生这种情况。

1 个答案:

答案 0 :(得分:1)

编辑:全新解决方案

终于找到了问题所在。基本上,从我所看到的,当你替换text的{​​{1}}时,它会将UITextField重置为字符串的最后(这是有道理的,因为那是光标所在的位置)是)。考虑到这一点,我能够提出以下代码,这些代码适用于iOS 6和7。

selectedTextRange

基本上发生的事情是从//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,从刚刚删除的字符前的字符开始。

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