键盘抬起时向上移动元素

时间:2013-01-12 01:31:56

标签: ios objective-c iphone xcode

我正在进行与以下功能类似的聊天:

enter image description here

当用户点击消息气泡时,我需要它来提升UITextField和UITableView(当然,在文本框上方有表格视图)。同样地,当他们发送或收回消息时,它应该回到原来的状态。

我尝试了here

发布的解决方案

两个通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillShowNotification object:nil];

实际功能:

- (void)keyboardWillHideOrShow:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];

    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect keyboardFrameForTextField = [self.myTextField.superview convertRect:keyboardFrame fromView:nil];

    CGRect newTextFieldFrame = self.myTextField.frame;
    newTextFieldFrame.origin.y = keyboardFrameForTextField.origin.y - newTextFieldFrame.size.height;

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | curve animations:^{
        self.myTextField.frame = newTextFieldFrame;
    } completion:nil];
}

但它有两个问题:

  1. 我不确定如何在键盘顶部提升桌面视图
  2. 键盘退回时,输入框完全消失。

1 个答案:

答案 0 :(得分:2)

这可能会有所帮助......不能因为它而受到赞扬,但对于我的生活,我无法记住它的来源......我曾经帮助过一个项目,所以这就是我使用它的方式。

当基于BOOL值YES或NO调用/解除键盘时,这将上下移动视图。这种方式还允许您对其他方面进行更多控制。

- (void) animateTextField: (UITextField*) textField up: (BOOL)up
{
const int movementDistance = 100;
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];
}

然后实施它:

-(IBAction)goingup:(id)sender
{
   //Bounces the text field up for editing
   [self animateTextField: yourtextfield up: YES];} 
}


-(IBAction)backdown:(id)sender
{
   //Bounces it back when keyboard is dismissed 
   [self animateTextField: yourtextfield up: NO];   
}

将操作连接到您的文本字段编辑确实已开始,编辑已完成终端,您已设置。

希望有所帮助。