键盘显示时向上移动UIView

时间:2011-03-07 14:24:26

标签: iphone uiview uiscrollview uitextfield

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

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

2 个答案:

答案 0 :(得分: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

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

将其导入您的UIViewController,然后您可以

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

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

......或者其他什么。该类别为您提供了三种调整视图位置的好方法。

答案 1 :(得分:1)

最简单的方法是将表单放在UITableViewCell中,然后将单元格放在UITableView上。如果那时,UITableView将自动处理大部分作品 ,与Apple应用程序完全相同。我在其他一些文章或答案中看到了这一点,但我不记得我在哪里看到这个。

但是我试图实现UITableView行为的模仿,这真是太难了。大多数功能都很简单,但在极少数情况下我无法复制特殊行为。所以我选择使用UITableView

相关问题