切换视图时选择UITableViewCell显示

时间:2012-10-18 11:49:27

标签: uitableview selection highlight

我有一个UITableViewCell,我希望在点击它时保持选中状态。所以我有这个代码可以正常工作:

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

static NSString *identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@", [[[self.dataSource objectAtIndex:indexPath.row] lastPathComponent] stringByDeletingPathExtension]];
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor brownColor]];
    [cell setSelectedBackgroundView:bgColorView];
    return cell;
}

每当我点击一个单元格时,它会被棕色选中并保持选中,直到我点击另一个单元格...完美 但是当我通过点击导航控制器的后退按钮关闭视图然后我切换回我的视图时,我的单元格不再被选中。那么,当我回到视图时,我怎样才能实现在切换视图之前选择的单元格仍被选中?

我想我可能要从tableview创建一个属性,然后再次选择viewDidLoad中的行。 selectedRow索引我可以保存在nsuserdefaults ..但我希望有一个更简单的解决方案。

1 个答案:

答案 0 :(得分:0)

-viewDidLoad方法中,将其添加到底部:self.clearsSelectionOnViewWillAppear = NO;这会使它看起来像这样:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.clearsSelectionOnViewWillAppear = NO;
}