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.


For the cell to appear selected, you have to call -setSelected:animated: from within -tableView:willDisplayCell:forRowAtIndexPath: like so:

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

Calling -setSelected from anywhere else has no effect.


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

Swift 4: Selecting cell initially

import UIKit

class MyViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    ...

     func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        if /* your code here */ == indexPath.row {
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableView.ScrollPosition.none)
        }
    }

    ...
}

I don't know you are expecting this answer. By default if you wants to select first row in your tableView with out manual selection, just initiate the didSelectRowAtIndexPath method like this

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