2015-04-20 43 views
1

我得到一個問題是,我想在鍵盤顯示時向上移動我的UIView(footerview),並在鍵盤被解散時將其移下。如何在鍵盤出現或關閉時移動包含在UIViewController中的UIView?

  • 我的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)]; 
} 
+0

後你有什麼到目前爲止已經試過。 – atulkhatri

+0

你想在文本框輸入時移動視圖 –

+0

是的,我想上下移動它。 – vichhai

回答

0

如果您使用Autolayout,您可以創建一個IBOutlet到您的UIView NSLayoutAttributeBottom約束,並在需要時進行更改。如果沒有,你必須移動你的視圖框架。

例如:

- (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]; 
    }]; 
} 
+0

我不擅長自動佈局。那麼你能告訴我任何來源來研究自動佈局嗎? – vichhai

+0

你可以谷歌它。有很多例子和教程。例如:http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1 – Bisca

相關問題