如何从视图外获取 UITableViewCell 并将其滚动到视图中 [英] How to get a UITableViewCell from out of view and scroll it into view
问题描述
在我的代码中,当用户向列表中添加新项目时,应用将其添加到项目数组中,对它们进行排序,然后调用 [tableView reloadData]
.由于对列表进行排序,有时新添加的项目会消失.当它不在视图中时,我将获取新添加项的 UITableViewCell
并将其滚动回视图.
In my code when user adds a new item to the list, the App adds it to an array of items, sorts them, then calls [tableView reloadData]
. Because of sorting the list, sometimes newly added item goes out of view. I'm going to get the UITableViewCell
of newly added item when it's out of view and scroll it back into view.
在 cellForRowAtIndexPath
中,我将记录添加到每个单元格的标签中:
In cellForRowAtIndexPath
I add the record to tag of each cell:
cell.tag = listItems.recordID;
在addNewItem
方法中添加新项目并对项目进行排序后:
In addNewItem
method after adding new item and sorting the items:
for (int i = 0; i<listItems.count; i++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
int tag = cell.tag;
if (tag == newItemRecordID)
[self.tableView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionMiddle
animated:YES];
}
当单元格不在视图中时 tag
属性返回 0
并且我无法获取单元格.
When the cell is out of view tag
property returns 0
and I can't get the cell.
怎么可能得到那个细胞?
How is it possible do get that cell?
推荐答案
我想,使用这样的东西会更好:
I guess, it would be better to use something like this:
for (int i = 0; i < listItems.count; i++)
{
// Replace 'ListItem' with the name of your class.
ListItem *listItem = [listItems objectAtIndex:i];
if (listItem.recordID == newItemRecordID)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionMiddle
animated:YES];
break;
}
}
这篇关于如何从视图外获取 UITableViewCell 并将其滚动到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!