我试图在键盘上方显示光标带有一些动画,同时尝试正确滚动UITextView背景线。
我已经使用下面的代码在iOS 7中解决了这个问题,但它在iOS 8上出现了问题,我认为原因是我试图在iOS8中覆盖 scrollRangeToVisible ,但我无法做到所以,不像iOS 7中那样自动调用。触摸UITextView时会显示键盘,因此我无法控制如何滚动内容。我的UITextView也有行。
- (void)textViewDidBeginEditing:(UITextView *)aTextView
{
caretVisibilityTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(scrollCaretToVisible) userInfo:nil repeats:NO];
}
- (void)textViewDidEndEditing:(UITextView *)aTextView
{
[caretVisibilityTimer invalidate];
caretVisibilityTimer = nil;
}
-(void) scrollRangeToVisible: (NSRange) range {
printf("scrollRangeToVisible \n");
}
- (void) scrollCaretToVisible {
printf("scrollCaretToVisible \n");
//[self becomeFirstResponder];
//This is where the cursor is at.
CGRect caretRect = [self caretRectForPosition: self.selectedTextRange.end];
if (CGRectEqualToRect(caretRect, oldRect))
return;
oldRect = caretRect;
//This is the visible rect of the textview.
CGRect visibleRect = self.bounds;
visibleRect.size.height -= (self.contentInset.top + self.contentInset.bottom);
visibleRect.origin.y = self.contentOffset.y;
//We will scroll only if the caret falls outside of the visible rect.
if (!CGRectContainsRect(visibleRect, caretRect)) {
CGPoint newOffset = self.contentOffset;
newOffset.y = MAX((caretRect.origin.y + caretRect.size.height) - visibleRect.size.height, 0);
//Added This section
//=======================================
// Calculates new contentOffset
if (caretRect.origin.y < visibleRect.origin.y)
// rect precedes bounds, scroll up
newOffset.y = caretRect.origin.y - self.contentInset.top - self.bottomPadding;
else
// rect follows bounds, scroll down
newOffset.y = caretRect.origin.y + self.contentInset.bottom + caretRect.size.height - self.bounds.size.height;
//=======================================
/* */
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^ (void)
//dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^(void)
{
[UIView beginAnimations: nil context: NULL];
[UIView setAnimationDuration: 0.5];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
[self setContentOffset: newOffset animated: YES];
[UIView commitAnimations];
});
//[self setContentOffset:newOffset animated:YES];
}
}
答案 0 :(得分:1)
如果有人有兴趣我发现对于iOS8我需要覆盖scrollRectToVisible,这相当于覆盖iOS7中的scrollRangeToVisible
iOS7
- (void) scrollRangeToVisible:(NSRange)range { }
iOS8上
- (void) scrollRectToVisible:(CGRect)rect animated:(BOOL)animated{ [self scrollCaretToVisible]; }