在我的應用程序中有幾種形式。有時鍵盤會隱藏字段,因此用戶無法看到他輸入的內容。對於這種情況,我找到了移動視圖或滾動視圖的方法,所以文本框保持在鍵盤上方。 問題是,在iPhone 5上,我需要將視圖向上移動到最後3個文本框,但對於iPhone 6 - 僅適用於最後一個文本框。鍵盤下的Textfields
corse我可以定義字段和設備屏幕高度值的所有情況。 但我想找到更優雅的解決方案來檢測texfield是否在當前設備的鍵盤下,是否有必要移動視圖?
在我的應用程序中有幾種形式。有時鍵盤會隱藏字段,因此用戶無法看到他輸入的內容。對於這種情況,我找到了移動視圖或滾動視圖的方法,所以文本框保持在鍵盤上方。 問題是,在iPhone 5上,我需要將視圖向上移動到最後3個文本框,但對於iPhone 6 - 僅適用於最後一個文本框。鍵盤下的Textfields
corse我可以定義字段和設備屏幕高度值的所有情況。 但我想找到更優雅的解決方案來檢測texfield是否在當前設備的鍵盤下,是否有必要移動視圖?
使用TPKeyboardAvoidingScrollView。它易於使用
的TPKeyboardAvoidingScrollView.m和TPKeyboardAvoidingScrollView.h源文件拖放到你的項目,彈出一個UIScrollView到您的視圖控制器的XIB,滾動視圖的類設置爲TPKeyboardAvoidingScrollView,並把那個滾動視圖中的所有控件。您也可以使用編程方式創建它,而不使用xib - 只需使用TPKeyboardAvoidingScrollView作爲頂層視圖。
謝謝。我絕對需要嘗試 – moonvader
有出自Apple here
你要聽鍵盤通知像
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
只適用於有滾動視圖時,不適用於有視圖時 –
原理仍然相同。您會收到通知,獲取鍵盤高度,查看選定的UITextField並查看是否需要將其容器視圖向上移動。 –
您可以檢測其UITextField
是「主動」一個使用它的委託方法- (void)textFieldDidBeginEditing:(UITextField *)textField
有很大的幫助指導。
使用textField.frame
來計算您需要爲scrollView.contentOffset
設置的偏移量。 在- textFieldDidBeginEditing:
方法可以重置contentOffset = CGPointZero
獲取鍵盤高度,看看屏幕上的文本字段的底部,底部越大比距離 – milo526
考慮使用其中每行都包含一個領域一個UITableView。當焦點移動到UITextField時,滾動到適當的UITableView行。 – Daniel