我刚开始学习编程iPhone应用程序,但似乎无法弄清如何在键盘出现时使视图滑动到一边(这样您仍然可以看到正在输入的文本字段)。这是如何完成的?
我刚开始学习编程iPhone应用程序,但似乎无法弄清如何在键盘出现时使视图滑动到一边(这样您仍然可以看到正在输入的文本字段)。这是如何完成的?
如果视觉效果良好,最简单的方法是移动整个self.view.frame,然后在完成后将其移回原位。
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3f;
- (void) animateForToNewYPosition:(int)newYPosition {
// move for kdb
if (self.view.frame.origin.y == newYPosition) {
return;
}
// start animation
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
// move it
self.view.frame.origin.y = newYPosition;
[UIView commitAnimations];
}
一个方法是将所有内容包含在UIScrollView中,然后向上滚动内容。另一种方法是自己移动视图,通常借助Core Animation使其看起来不错。
开始的好地方是文档。甚至有一个帮助标签为移动位于键盘下方的内容的部分,它将指导您朝正确的方向前进。
http://objectivecwithsuraj.blogspot.in/2012/06/making-view-slide-up-to-make-room-for.html
Add a UIScrollview - scrollview to your UIView and set delegates for UITextFields &
UIScrollview
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == txtFieldName)
{
[txtFieldCellNo becomeFirstResponder];
}
else if (textField == txtFieldCellNo)
{
[txtFieldEmail becomeFirstResponder];
}
else
{
[textField resignFirstResponder];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField:txtFieldName up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField:txtFieldEmail up:NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 80;
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame,0, movement);
[UIView commitAnimations];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textField.tag==4)
CGRect viewFrame;
viewFrame=self.view.frame;
if(viewFrame.origin.y==-100)
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
viewFrame.origin.y+=100;
self.view.frame=viewFrame;
[UIView commitAnimations];
}
}
这会移动你的视图。现在,如果要向下移动,你需要在textField中编写另一个委托方法的代码。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField.tag==4)
{
CGRect viewFrame;
viewFrame=self.view.frame;
if(viewFrame.origin.y==-100)
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.3];
viewFrame.origin.y+=100;
self.view.frame=viewFrame;
[UIView commitAnimations];
}
}
}
针对TextView,您需要一个按钮,并且为了向上移动您的视图,您需要该委托。
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
使用与textField相同的代码
向下移动时,您需要一个按钮,可以放在导航栏中或添加到工具栏中,并通过相同的动画将该工具栏设置在键盘上方。对于按钮,您需要适用于textField的相同移动代码。
希望这可以帮助您。