UITableView 滚动到错误的位置
Posted
技术标签:
【中文标题】UITableView 滚动到错误的位置【英文标题】:UITableView scrolls to wrong position 【发布时间】:2020-02-20 17:13:01 【问题描述】:我有一个UITableView
,我插入了很多单元格。每个单元格包含一个UITextField
。我想自动滚动到焦点UITextField
。但是如果我删除一个单元格,UITableView
无法滚动到正确的UITextField
,键盘与焦点UITextField
重叠
[super viewDidLoad];
// Do any additional setup after loading the view.
[self registerForKeyboardNotifications];
cellArray = [[NSMutableArray alloc] initWithObjects:_cell0, _cell1, _cell2, _cell3, _cell4, _cell5, _cell6, _cell7, _cell8, _cell9, _cell10, _cell11, _cell12, _cell13, _cell14, _cell15, nil];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
return [cellArray count];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
return [cellArray objectAtIndex:indexPath.row];
- (void)textFieldDidBeginEditing:(UITextField *)textField
if (textField == _input0)
[cellArray removeObject:_cell1];
[_tableView reloadData];
activeField = textField;
- (void)textFieldDidEndEditing:(UITextField *)textField
activeField = nil;
- (void)registerForKeyboardNotifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWasShown:(NSNotification*)aNotification
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+100, 0.0);
_tableView.contentInset = contentInsets;
_tableView.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) )
[_tableView scrollRectToVisible:activeField.frame animated:YES];
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_tableView.contentInset = contentInsets;
_tableView.scrollIndicatorInsets = contentInsets;
```
【问题讨论】:
所以问题是由[cellArray removeObject:_cell1]; [_tableView reloadData];
引起的,那不是如何删除单元格。当用户在其中编辑时删除一个单元格有点疯狂。如果你对我这样做,我会删除你的应用程序。
啊,是的,我疯了,谢谢!
【参考方案1】:
// 删除索引路径处的行 [m_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
// 在索引路径插入行 [m_tableView insertRowsAtIndexPaths:@[m_indexPath] withRowAnimation:UITableViewRowAnimationFade];
【讨论】:
以上是关于UITableView 滚动到错误的位置的主要内容,如果未能解决你的问题,请参考以下文章
编辑第一个 UITextField 时,如何将 UITableView 滚动到第二个 UITextField?