如何从视图中获取UITableViewCell并将其滚动到视图中

时间:2014-04-27 13:51:03

标签: ios uitableview

在我的代码中,当用户向列表中添加新项目时,应用程序会将其添加到项目数组中,对其进行排序,然后调用[tableView reloadData]。由于对列表进行排序,有时新添加的项目会消失。当它不在视图中时,我将获得新添加项目的UITableViewCell并将其滚动回视图。

cellForRowAtIndexPath中,我将记录添加到每个单元格的标记中:

cell.tag = listItems.recordID;

在添加新项目并对项目进行排序后的addNewItem方法中:

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而我无法获取单元格。

怎样才能获得那个细胞?

2 个答案:

答案 0 :(得分:1)

我想,最好使用这样的东西:

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;
    }
}

答案 1 :(得分:0)

cellForRowAtIndexPath设置单元格标记如下:

cell.tag = indexPath.row;

设置单元格标记后,您可以调用您的函数:

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];
}