如何在UITableView中移动没有NSIndexPath的单元格?

时间:2014-03-27 03:49:51

标签: ios objective-c uitableview

我将在UITableView中将一个单元格从一个部分移动到另一个部分。问题是我不知道这个单元格的索引路径。 (换句话说,我有一个这个单元格的索引路径,但索引路径现在可能已过期)。相反,我有一个参考点指向这个单元格。我该如何移动这个细胞?

提前感谢。

2 个答案:

答案 0 :(得分:1)

如果您有对单元格对象的引用,那么您只需获取其索引路径。

UITableViewCell *cellObject; //provided that you have a reference to it.
NSIndexPath *indexPath = [tableView indexPathForCell:cellObject];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

答案 1 :(得分:1)

以下是如何基于在单元格中找到某个字符串到第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]];
    }
}