繁体   English   中英

当键盘出现或关闭时,如何移动UIViewController中包含的UIView?

[英]How to move UIView that contain in UIViewController when keyboard appear or dismiss?

我有一个问题是我想在显示键盘时将UIView(footerview)向上移动,而在关闭键盘时将其向下移动。

  • 我的UIView(FooterView)包含在Xcode自动生成的Main.Storyboard的UIViewController中。
  • 我也有一个TextField。

视图层次结构将如下所示:

视图:

- >文本字段

-> UIView(FooterView)

编辑

发布此问题后,我自己找到了答案

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
return YES;
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];

[self.view endEditing:YES];
return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)keyboardDidShow:(NSNotification *)notification
{
// Assign new frame to view
[self.footerView setFrame:CGRectMake(0,250,320,65)];
}

-(void)keyboardDidHide:(NSNotification *)notification
{
// set it back to the original place
[self.footerView setFrame:CGRectMake(0,503,320,65)];
}

如果使用的是自动布局,则可以为UIView NSLayoutAttributeBottom约束创建一个IBOutlet并在需要时进行更改。 如果不是,则必须移动视图框架。

例如:

- (void)keyboardWillShow:(NSNotification *)notification {
    // Get the size of the keyboard.
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    self.bottomConstraintKeyboard = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.writeView attribute:NSLayoutAttributeBottom multiplier:1 constant:keyboardSize.height];
     [self.view removeConstraint:self.bottomConstraintZero];
    [self.view addConstraint:self.bottomConstraintKeyboard];
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];    
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (self.bottomConstraintKeyboard){
        [self.view removeConstraint:self.bottomConstraintKeyboard];
        self.bottomConstraintKeyboard = nil;
    }
    [self.view addConstraint:self.bottomConstraintZero];
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM