I am trying to display the cursor above the keyboard with some animation also trying to scroll the UITextView background lines correctly.
I had solved this problem in iOS 7 perfercly using the code below but it broke on iOS 8, I think the reason is that I am trying to override scrollRangeToVisible in iOS8 but I am unable to do so, its not called automatically like in iOS 7. The keyboard is displayed the moment the UITextView is touched, so I don't have control over how to scroll things. my UITextView has lines as well.
- (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];
}
}