Search code examples
iosuitableviewuisplitviewcontroller

UITableViewCell Set selected initially


Hi there I have situation where in an iPad app my master controller has list and details controller have its details , a typical UISplitViewController pattern. What I want to achieve is , my first row should be initially selected and later I want to give selection choice to user. I am using cell's setSelected and in didSelectRowAtIndexPath method removing selection like this.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSIndexPath* path = [NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:path];
    [cell setSelected:NO];
} 

for initial cell but my none cell is getting selected after that please help me out.


Solution

  • try this

    NSIndexPath* selectedCellIndexPath= [NSIndexPath indexPathForRow:0 inSection:0];
    [self tableView:tableViewList didSelectRowAtIndexPath:selectedCellIndexPath];
    [tableViewList selectRowAtIndexPath:selectedCellIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    

    OR

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

    Swift 4 version is

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        func shouldSelect() -> Bool {
            // Some checks
        }
        if shouldSelect() {
                tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        }
    }