Reputation: 989
I am going to move a cell from a section to another in UITableView. The problem is that I don't know the index path of this cell. (Or in other words, I have an index path for this cell but the index path is likely out of date now). Instead, I have a reference point to this cell. How can I move this cell?
thanks in advance.
Upvotes: 0
Views: 224
Reputation: 104092
Here is an example of how to move a row based on finding a certain string in the cell to the top of section 1.
@implementation TableController {
NSInteger selectedRow;
NSMutableArray *theData;
}
-(void)viewDidLoad {
[super viewDidLoad];
self.tableView.contentInset = UIEdgeInsetsMake(70, 0, 0, 0);
NSMutableArray *colors = [@[@"Black", @"Brown", @"Red", @"Orange", @"Yellow",@"Green", @"Blue"] mutableCopy];
NSMutableArray *nums = [@[@"One", @"Two", @"Three", @"Four", @"Five", @"Six", @"Seven", @"Eight"] mutableCopy];
theData = [@[colors, nums] mutableCopy];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return theData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [theData[section] count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return (section == 0)? @"Colors" : @"Numbers";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = theData[indexPath.section][indexPath.row];
return cell;
}
-(IBAction)moveRow:(id)sender {
NSString *objToMove = @"Red";
// Find the section that contains "Red"
NSInteger sectionNum = [theData indexOfObjectPassingTest:^BOOL(NSArray *obj, NSUInteger idx, BOOL *stop) {
return [obj containsObject:objToMove];
}];
// Find the row that contains "Red"
NSInteger rowNum = [theData[sectionNum] indexOfObjectIdenticalTo:objToMove];
if (sectionNum != NSNotFound && rowNum != NSNotFound) {
[theData[sectionNum] removeObjectIdenticalTo:objToMove];
[theData[1] insertObject:objToMove atIndex:0];
[self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:rowNum inSection:sectionNum] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
}
}
Upvotes: 1
Reputation: 413
If you have a reference to the cell's object then you can simply get its indexpath.
UITableViewCell *cellObject; //provided that you have a reference to it.
NSIndexPath *indexPath = [tableView indexPathForCell:cellObject];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
Upvotes: 1