我是 iOS 新手。我正在制作一个聊天应用程序,所以我在 UITableView
下面有一个 UITextField
并且 UITextField
和 UITableView
在 UIScrollView
(我已通过 self.scrollView.scrollEnabled = NO;
禁用 ScrollView 中的滚动)。
当我点击 UITextField
时,会显示键盘,所以我将 UITextField
移动到键盘上方,然后按照 Managing the Keyboard doc
// 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);
self.scrollView.contentInset = contentInsets;
self.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, self.activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:self.activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.activeField = nil;
}
使用这段代码,我的 TextField
成功移动到键盘上方
但问题是:在 TableView
中,当显示键盘时,我无法滚动查看顶部的某些项目(大约 2 个项目)。
例如,如果我的 tableview 有 10 个项目,当显示键盘时,我只能看到 8 个项目,其余 2 个项目仍然存在,但我无法滚动到它们
这是我的 Demo Project
我认为 UITableView
的内容插图可能是错误的,但我不知道如何修复它。
任何帮助将不胜感激
最佳答案
使用 Autolayout
代替 contentInsets
在ViewController.h
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *botConstraint;
在ViewController.m
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
self.botConstraint.constant = kbSize.height;
[self.view layoutIfNeeded];
//...
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
self.botConstraint.constant = 0.0f;
[self.view layoutIfNeeded];
//...
}
botConstraint
是 UITextField
/UITableView
/UIScrollView
.bottom
= fatherView
.bottom
在你的 Main.storyboard
关于IOS:UITextField+UITableView inside UIScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36465850/