Move UIView up when the keyboard appears in iOS

后端 未结 18 1814
再見小時候
再見小時候 2020-11-28 20:38

I have a UIView, it is not inside UIScrollView. I would like to move up my View when the keyboard appears. Before I tried to use this solution: How can I make a UITextField

18条回答
  •  渐次进展
    2020-11-28 21:03

    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 
    
    @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.

提交回复
热议问题