当键盘弹出时,将表单向上滑动

4

你好,我正在使用一个表单进行数据输入,表单中有一些文本字段位于底部。当我点击文本字段进行输入时,键盘会出现并将这些字段隐藏在后面。如果我让文本字段成为第一个响应者,它会隐藏键盘,但这样做会导致我不能完成输入操作。我想知道如何实现:当键盘出现时,整个表单应该向上移动,使得最后一个字段出现在键盘的顶部。谢谢!


3个回答

6

将所有的视图添加到一个滚动视图中,并设置滚动视图和文本字段的代理,然后使用这些代理和方法-

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

   [self scrollViewToCenterOfScreen:textField];     
    return YES;

}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{

    if ([textField isEqual:txtField1])
    {
        [txtField2 becomeFirstResponder];
    }
    else if ([textField isEqual:txtField2])
    {
        [txtField3 becomeFirstResponder];
    }
    else 
    {
        [textField resignFirstResponder];       
        [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }

    return YES;

}

- (void)scrollViewToCenterOfScreen:(UIView *)theView {  
    CGFloat viewCenterY = theView.center.y;  
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];  

    CGFloat availableHeight = applicationFrame.size.height - 200;            // Remove area covered by keyboard  

    CGFloat y = viewCenterY - availableHeight / 2.0;  
    if (y < 0) {  
        y = 0;  
    }  
    [scrollView setContentOffset:CGPointMake(0, y) animated:YES];  

}

1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接