键盘显示时向上移动UIView

Dan*_*Dan 3 iphone uiscrollview uitextfield uiview

我知道这是一个经常出现的问题,但我没有从我发现的例子中实现这一点.我可能会做一些简单的错误..(希望如此).我试图将UIview移动到底部隐藏文本字段.

关于我的应用程序,它有一个标签栏控制器,并实现了标准的UIView.当我添加代码移动显示时没有任何反应.我需要有一个滚动视图才能使用它,它是否与制表符控制器发生冲突,或者我在做其他错误的操作?谢谢

Dan*_*Ray 6

我在UIView上写了一个小类,它管理暂时滚动的东西,而不需要将整个东西包装到UIScrollView中.我在这里使用动词"scroll"可能并不理想,因为它可能会让你认为有一个滚动视图,而且没有 - 我们只是动画UIView(或UIView子类)的位置.

这里嵌入了许多魔法数字,这些数字适合我的形式和布局,可能不适合你的,所以我鼓励调整它以满足您的特定需求.

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

将其导入到UIViewController中,然后就可以了

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.view scrollToView:textField];
}

-(void) textFieldDidEndEditing:(UITextField *)textField
{
    [self.view scrollToY:0];
    [textField resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

...管他呢.该类别为您提供了三种调整视图位置的好方法.