UITextView光标在iOS 7中编辑时没有正确定位。为什么?

为什么这是一件事情发生

上面的黄色框是一个可编辑的当前正在编辑的UITextView(是第一个响应者)。 但你可能说不清楚? 因为没有光标。 但是有…这是黄色textView左下方的小蓝点。 它略低于textViews底部边界。 所以如果我不断地换一个新的行,或者按下回车键,文字就会自然而然的向上移动。 但是游标永远不会“水平”,或者在UITextView的底部边界之上。 它总是勉强地从底部开始,在边界以下几点。

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

这个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]; }]; } } 

你的问题将解决。

如果你在导航控制器场景中,我认为这实际上是iOS 7中引入的属性的结果: automaticallyAdjustsScrollViewInsets (请参阅iOS 7转换指南 )

这个默认是YES,并且会通过调整导航控制器的高度的滚动偏移来尝试使用UITextView(它本身就是一个滚动视图)。

因此,解决方法是在viewDidLoad将此属性设置为NO(注意不要在iOS 6上调用它,因为它仅适用于iOS 7)。

基于Todd给出的答案,你可以在应用程序完成启动时运行的方法中放入类似这样的东西:

  [[UITextView appearance] setTintColor:[UIColor redColor]]; [[UITextField appearance] setTintColor:[UIColor redColor]]; 

这将影响所有的UITextFields和UITextViews。

 - (BOOL) textView:(UITextView *)sender shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { NSString * newText = [sender.text stringByReplacingCharactersInRange:range withString:text]; [self setFramesForText:newText]; if (!IOS_VERSION_6_OR_LESS) { if ([text isEqualToString:@"\n"]){ [textView setContentOffset:CGPointMake(textView.contentOffset.x, 999999999)]; } } return YES; } 

你只需要设置UITextView的tintColor。

在代码中放入类似下面的代码(我把它放在viewDidLoad中)为我工作。

 self.textView.tintColor = [UIColor redColor];