【问题标题】:How to move UIView that contain in UIViewController when keyboard appear or dismiss?键盘出现或关闭时如何移动包含在 UIViewController 中的 UIView?
【发布时间】:2015-04-20 18:03:57
【问题描述】:

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

  • 我的 UIView (FooterView) 包含在 Main.Storyboard 的 UIViewController 中,由 Xcode 自动生成。
  • 我也有一个 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)];
}

【问题讨论】:

标签: ios uiview uikeyboard


【解决方案1】:

如果您使用自动布局,您可以为您的 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];
    }];
}

【讨论】:

  • 我不擅长自动布局。那么你能告诉我任何研究自动布局的资料吗?
  • 你可以谷歌一下。有很多例子和教程。例如:raywenderlich.com/50317/…
猜你喜欢
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2011-12-18
  • 2012-07-02
相关资源
最近更新 更多