I've got UItableview and also two buttons Next and Previous tapping on which I should go to the selection of the previous/next cell? is it possible? Moreover, how to remember the cell the user last tapped so that it is selected on start-up?
Implement UITableViewDelegate and save the currently selected index in didSelectRowAtIndexPath:
NSIndexPath *currentSelection;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
currentSelection = indexPath;
}
Then in your button action you can do something like...
- (IBAction)didTapNextButton:(id)sender{
//Remember to check boundaries before just setting an indexpath or your app will crash!
if(currentSelection){
currentSelection = [NSIndexPath indexPathForRow:currentSelection.row+1 inSection:currentSelection.section];
}else{
currentSelection = [NSIndexPath indexPathForRow:0 inSection:0];
}
[self.tableView selectRowAtIndexPath:currentSelection animated:YES scrollPosition: UITableViewScrollPositionTop];
}
Here are a couple of UITableView
category methods that can find the next/previous NSIndexPath
from a specified NSIndexPath
.
These methods accommodate sections and empty sections.
@interface (.h)
@interface UITableView(Extensions)
- (NSIndexPath *)nextIndexPathFromIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)prevIndexPathFromIndexPath:(NSIndexPath *)indexPath;
@end
@implementation (.m)
@implementation UITableView(Extensions)
-(NSIndexPath *)nextIndexPathFromIndexPath:(NSIndexPath *)indexPath {
return [self adjacentIndexPathFromIndexPath:indexPath goingForward:YES];
}
-(NSIndexPath *)prevIndexPathFromIndexPath:(NSIndexPath *)indexPath {
return [self adjacentIndexPathFromIndexPath:indexPath goingForward:NO];
}
-(NSIndexPath *)adjacentIndexPathFromIndexPath:(NSIndexPath *)indexPath goingForward:(BOOL)goingForward {
NSInteger delta = goingForward ? 1 : -1;
NSInteger adjRow = indexPath.row + delta;
if (adjRow >= 0 && adjRow < [self numberOfRowsInSection:indexPath.section]) {
//Adjacent row in same section...
return [NSIndexPath indexPathForRow:adjRow inSection:indexPath.section];
}
NSInteger adjSection = indexPath.section + delta;
if (adjSection < 0) {
adjSection = [self numberOfSections] - 1;
} else if (adjSection > [self numberOfSections] - 1) {
adjSection = 0;
}
NSUInteger adjSectionRows = [self numberOfRowsInSection:adjSection];
if (!adjSectionRows) {
//Adjacent section is empty...
//Adjacent row in adjacent-adjacent section...
return [self adjacentIndexPathFromIndexPath:[NSIndexPath indexPathForRow:0 inSection:adjSection] goingForward:goingForward];
}
adjRow = goingForward ? 0 : adjSectionRows - 1;
//Adjacent row in adjacent section...
return [NSIndexPath indexPathForRow:adjRow inSection:adjSection];
}
@end
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