UITableViewCell Set selected initially UITableViewCell Set selected initially ios ios

UITableViewCell Set selected initially


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