【问题标题】:Manually select row in UITableView using selectRowAtIndexPath使用 selectRowAtIndexPath 在 UITableView 中手动选择行
【发布时间】:2015-10-27 21:24:00
【问题描述】:

所以我尝试使用 selectRowAtIndexPath 预先选择表中的一行。

我的问题是,调用 selectRowAtIndexPath 的最佳位置在哪里?

我想调用它的唯一地方是在 cellForRowAtIndexPath:... 因为我有 indexPath,但这似乎不起作用。

感谢任何答案或建议。

谢谢!

【问题讨论】:

  • viewWillAppear: 将是一个常见的地方。

标签: ios objective-c uitableview cocoa-touch


【解决方案1】:

方法一

要使单元格显示为选中状态,您必须从 -tableView:willDisplayCell:forRowAtIndexPath: 中调用 -setSelected:animated:,如下所示:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (/* Condition */) {
        [cell setSelected:YES animated:NO];
    }
}

方法2

- (void)viewDidAppear:(BOOL)animated {
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionNone];
}

如果您希望每次都选择该特定行,那么 方法 1 会更好,否则如果您只想最初选择该行,那么方法 2 更好。

【讨论】:

  • 啊,谢谢,我接近 2 正是我想要的!
【解决方案2】:

为什么不直接将单元格设置为手动选中,而不是调用委托方法?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
    //...
    if( /* some condition */ ) {
        cell.selected = YES;
    }
    //...
    return cell;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2010-11-13
    相关资源
    最近更新 更多