How to scroll table view with toolbar at the top of the view
I have a view with a toolbar at the top and a table view with text fields in it's cells. When I want to edit the text fields placed in the bottom of the table view the keyboard is hiding the text field being edited (as the table view is not scrolled up). I tried to implement http://cocoawithlove.com/2008/10/sliding-uitextfields-around-to-avoid.html but this makes my whole view move up (the toolbar and the table view) while I would like to have the toobar at the top of the view for the whole time. I modified the mentioned code to something like this:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
CGRect textFieldRect = [tableView.window convertRect:textField.bounds fromView:textField];
CGRect viewRect = [tableView.window convertRect:tmpTableView.bounds fromView:tableView];
CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
CGFloat heightFraction = numerator / denominator;
if (heightFraction < 0.0) {
heightFraction = 0.0;
} else if (heightFraction > 1.0) {
heightFraction = 1.0;
}
UIInter开发者_如何学JAVAfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
} else {
animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
}
CGRect viewFrame = tableView.frame;
viewFrame.origin.y -= animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[tableView setFrame:viewFrame];
[UIView commitAnimations];
}
and
- (void)textFieldDidEndEditing:(UITextField *)textField {
CGRect viewFrame = tableView.frame;
viewFrame.origin.y += animatedDistance;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[tableView setFrame:viewFrame];
[UIView commitAnimations];
}
This made my toolbar stay at the top, but unfortunately the table view overlays the toolbar and the toolbar is not visible.
Any ideas how to solve this?
Instead of repositioning the table view, you should resize it so that the keyboard does not overlap it.
精彩评论