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.
- (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.
Swit 3.0 updated Solution
let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
- (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];
}
- (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];
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With