Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select First Row as default in UITableView

I have an application that is viewbased and I am adding a tableview as a subview to the main view. I have taken UITableViewDelegate to respond the table methods. Everything is working fine, but I want to select the first row or UITableView as default selected(Highlighted).

Please help me, with what code I need and where I need to put it.

like image 838
tushar maniyar Avatar asked Apr 28 '10 09:04

tushar maniyar


5 Answers

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

The best way to use this in your code, if you want to select any row by default, use in viewDidAppear.

like image 128
Zain Raza Avatar answered Oct 13 '22 21:10

Zain Raza


Swit 3.0 updated Solution

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
like image 28
Sourabh Sharma Avatar answered Oct 13 '22 22:10

Sourabh Sharma


- (void)viewWillAppear:(BOOL)animated
    {

       [super viewWillAppear:animated];

     // assuming you had the table view wired to IBOutlet myTableView

        // and that you wanted to select the first item in the first section

        [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
    }
like image 40
Ankit Vyas Avatar answered Oct 13 '22 22:10

Ankit Vyas


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];

    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    }
}
like image 5
malhal Avatar answered Oct 13 '22 23:10

malhal


Swift 4 Update:

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let indexPath = IndexPath(row: 0, section: 0)
    myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
}

Change row and section values if you want to select any other row in a different section.

like image 5
Sanket Ray Avatar answered Oct 13 '22 23:10

Sanket Ray