我遇到的一个问题是,我想在键盘显示时向上移动我的UIView(footerview)并在键盘被解除时将其向下移动。
查看层次结构将如下所示:
查看:
- > 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)];
}
答案 0 :(得分:0)
如果您使用的是Autolayout,您可以为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];
}];
}