来自另一个UIVIewController的selectRowAtIndexPath不起作用

时间:2014-04-12 01:46:45

标签: ios objective-c uitableview uiviewcontroller

我试图在UITableView上调用 selectRowAtIndexPath ,这是我调用它的UIViewController的子视图。

我已经设置了它,以便当你选择一个单元格时它会变灰并且很好,但是我在UITableView中加载和加载不同的数据集,当我做出选择时,我将选择的NSIndexPath发送回UIViewController。然后当下一个视图加载了NSIndexPath的正确数据集时,我从我的UIViewController调用此方法。

if (codeIndexPath != nil) {
            [filterViewController.tableView selectRowAtIndexPath:codeIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}

然后在UITableView类中,我的 cellForRowAtIndexPath didSelectRowAtIndexPath 看起来像这样。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell...
    NSString *projectDescriptionString = [currentFilterMutableArray objectAtIndex:indexPath.row];
    cell.textLabel.text = projectDescriptionString;
    if (indexPath == currentlySelectedIndex) {
        cell.highlighted = YES;
    } else if (indexPath == currentlySelectedIndex) {
        cell.highlighted = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    // send this data back in the delegate so you can use it to show where the tick is again if you need too.
    currentlySelectedIndex = indexPath;

    [[self delegate] updateInstallTableWithFilter:[currentFilterMutableArray objectAtIndex:indexPath.row] FilterType:filterType InstallIndex:indexPath];

}

当它在屏幕上加载时,正确的单元格将突出显示一秒钟,然后返回白色。

更新

如果在cellForRowAtIndexPath

中有新的if语句
if ([indexPath isEqual:currentlySelectedIndex]) {
        cell.highlighted = YES;
    } else if (![indexPath isEqual:currentlySelectedIndex]) {
        cell.highlighted = NO;
    }

我仍然收到同样的错误。

1 个答案:

答案 0 :(得分:4)

UITableViewController有一个名为clearsSelectionOnViewWillAppear的属性。 From the doc

  

当表格视图即将在第一次加载时出现时,   table-view controller重新加载表视图的数据。它也清除了   它的选择(有或没有动画,取决于要求)   每次显示表格视图。 UITableViewController   class在超类方法viewWillAppear中实现它:您   可以通过更改中的值来禁用此行为   clearsSelectionOnViewWillAppear property。

所以在那个表视图控制器子类中,在viewDidLoad ...

- (void)viewDidLoad {
    [super viewDidLoad];
    self.clearsSelectionOnViewWillAppear = NO;
}