在iOS 7中编辑时,UITextView光标无法正确定位.为什么?

Joe*_*Joe 23 uiscrollview uitextview ios ios7

为什么会发生这种情况

上面的黄色框是一个可编辑的UITextView,当前正在编辑(是第一响应者).但你可能说得对不对?因为没有光标.但是有......这是黄色textView左下角的小蓝点.它略低于textViews底部边框.因此,如果我继续使用新行,或按Enter键,文本将自然地向上移动.但是光标永远不会"水平",或者在UITextView的下边框正上方.它总是从底部勉强伸出,在边界下面几个点.

为什么?这在iOS 6中不是问题.有什么方法可以解决这个问题吗?

Pra*_*tik 41

这个bug在iOS 7.0中你可以通过修改textView委托方法来解决这个问题.

尝试以下代码

- (void)textViewDidChange:(UITextView *)textView {
    CGRect line = [textView caretRectForPosition:
        textView.selectedTextRange.start];
    CGFloat overflow = line.origin.y + line.size.height
        - ( textView.contentOffset.y + textView.bounds.size.height
        - textView.contentInset.bottom - textView.contentInset.top );
    if ( overflow > 0 ) {
    // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
    // Scroll caret to visible area
        CGPoint offset = textView.contentOffset;
        offset.y += overflow + 7; // leave 7 pixels margin
    // Cannot animate with setContentOffset:animated: or caret will not appear
        [UIView animateWithDuration:.2 animations:^{
            [textView setContentOffset:offset];
        }];
    }
}
Run Code Online (Sandbox Code Playgroud)

你的问题会解决.

  • Pratik的答案在CGRect line = [textView caretRectForPosition:textView.selectedTextRange.start]崩溃,其中line.origin.y作为inf返回.任何人都有解决此崩溃问题的方法吗? (2认同)
  • @Shilpi完全正确,在某些情况下,此代码**将崩溃**.虽然我还没有调试它.使if语句成为`if(overflow> 0 &&!isnan(line.origin.y)&&!isinf(line.origin.y))`直到进一步调试,这至少可以防止崩溃在文本视图的`setContentOffset:`里面. (2认同)