簡體   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