[英]How to move view at the center of visible frame when keyboard appears?
我在根滾動視圖中嵌入了一個標准的UIView
(包含一個圖像視圖,兩個文本字段和一個按鈕)。 我正在使用AutoLayout將UIView
放在滾動視圖的中心,如下面的屏幕快照所示。
我正在嘗試編寫一種方法,當鍵盤出現時,該方法將UIView
向上移動,以便該視圖將出現在較小可見框的中心。 為此,我計算了一些高度。
- (void)keyboardWillShow:(NSNotification *)notification {
// Determines the size of the keyboard frame
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
[UIView animateWithDuration:0.3 animations:^{
// Gets the root 'UIView' frame and stores it in a variable
CGRect viewFrame = self.itemsView.frame;
// This is the height of the visible frame once the keyboard appears
double visibleFrameHeight = (self.view.frame.size.height - keyboardSize.height);
// How much the 'UIView' should move up
double offset = ((visibleFrameHeight - viewFrame.size.height / 2);
// Moves up the 'UIView'
viewFrame.origin.y = -offset;
self.itemsView.frame = viewFrame;
}];
}
問題在於UIView
太上移,如下所示。
為什么會發生這種情況,我該如何解決?
如果您的視圖已經嵌入UIScrollView中,則只需調整滾動視圖的contentOffset
即可移動視圖(然后您可以免費獲得動畫)。
假設scrollview在名為scrollView
的插座上scrollView
,並且您想使視圖居中,則只需將內容偏移量移動鍵盤高度的1/2。 另外-使用UIKeyboardFrameEndUserInfoKey
來獲取鍵盤的最后一幀可能更安全:
- (void)keyboardWillShow:(NSNotification *)notification {
// Determines the size of the keyboard frame
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
self.scrollView.contentOffset = CGPointMake(0, keyboardSize.height / 2);
}
- (void)keyboardWillHide:(NSNotification *)notification {
self.scrollView.contentOffset = CGPointZero;
}
您必須像這樣在.h文件中為UIScrollView設置一個IBOutlet: IBOutlet UIScrollView * scrLogin;
然后在您的xib文件中為UIScrollview和所有UiTextfield設置委托 。
然后在您的.m文件中設置此代碼后
您已經設置了所有設計,如UIimageview,UItextfield和UIButton以及UIScrollView中的所有內容。
- (void)viewDidLoad {
[scrLogin setContentSize:CGSizeMake(320, 790)];
[scrLogin setContentOffset:CGPointMake(0, 0) animated:YES];
}
#pragma mark - Textfield Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField==txtUserName) {
[txtUserName resignFirstResponder];
[txtPsw becomeFirstResponder];
}else{
[txtPsw resignFirstResponder];
[scrLogin setContentOffset:CGPointMake(0, -60) animated:NO];
//[self btnLoginTapped:self];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
if(textField==txtUserName){
if (IS_IPHONE_4s) {
[scrLogin setContentOffset:CGPointMake(0, 20) animated:true];
}else{
[scrLogin setContentOffset:CGPointMake(0, 0) animated:true];
}
}else if(textField==txtPsw){
[scrLogin setContentOffset:CGPointMake(0, 40) animated:true];
}
}
希望對您有幫助。 如果您有任何問題,請告訴我。
我建議使用https://github.com/hackiftekhar/IQKeyboardManager ,它易於使用並且可在您的整個應用程序中使用(無需再次手動計算鍵盤高度)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.