I wrote a little category on UIView that manages temporarily scrolling things around without needing to wrap the whole thing into a UIScrollView. My use of the verb "scroll" here is perhaps not ideal, because it might make you think there's a scroll view involved, and there's not--we're just animating the position of a UIView (or UIView subclass).
There are a bunch of magic numbers embedded in this that are appropriate to my form and layout that might not be appropriate to yours, so I encourage tweaking this to fit your specific needs.
UIView+FormScroll.h:
#import <Foundation/Foundation.h>
@interface UIView (FormScroll)
-(void)scrollToY:(float)y;
-(void)scrollToView:(UIView *)view;
-(void)scrollElement:(UIView *)view toPoint:(float)y;
@end
UIView+FormScroll.m:
#import "UIView+FormScroll.h"
@implementation UIView (FormScroll)
-(void)scrollToY:(float)y
{
[UIView beginAnimations:@"registerScroll" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.4];
self.transform = CGAffineTransformMakeTranslation(0, y);
[UIView commitAnimations];
}
-(void)scrollToView:(UIView *)view
{
CGRect theFrame = view.frame;
float y = theFrame.origin.y - 15;
y -= (y/1.7);
[self scrollToY:-y];
}
-(void)scrollElement:(UIView *)view toPoint:(float)y
{
CGRect theFrame = view.frame;
float orig_y = theFrame.origin.y;
float diff = y - orig_y;
if (diff < 0) {
[self scrollToY:diff];
}
else {
[self scrollToY:0];
}
}
@end
Import that into your UIViewController, and then you can do
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self.view scrollToView:textField];
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
[self.view scrollToY:0];
[textField resignFirstResponder];
}
...or whatever. That category gives you three pretty good ways to adjust the position of a view.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…