我将在UITableView中将一个单元格从一个部分移动到另一个部分。问题是我不知道这个单元格的索引路径。 (换句话说,我有这个单元格的索引路径,但索引路径可能已经过时了)。相反,我有一个参考点,这个单元格。我如何移动这个单元格?如何在UITableView中移动没有NSIndexPath的单元格?
在此先感谢。
我将在UITableView中将一个单元格从一个部分移动到另一个部分。问题是我不知道这个单元格的索引路径。 (换句话说,我有这个单元格的索引路径,但索引路径可能已经过时了)。相反,我有一个参考点,这个单元格。我如何移动这个单元格?如何在UITableView中移动没有NSIndexPath的单元格?
在此先感谢。
这里是如何通过“参考点移动基于发现在细胞中某些字符串到部分顶部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]];
}
}
从数据源中找到新鲜的indexpath的绝佳解决方案。非常感谢。 –
如果你有一个单元格的对象的引用,那么你可以简单地得到它的索引路径。
UITableViewCell *cellObject; //provided that you have a reference to it.
NSIndexPath *indexPath = [tableView indexPathForCell:cellObject];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
谢谢,我今晚会测试你的代码。顺便说一句,'[tableView indexPathForCell:cellObject]'可能会返回零如果单元格不可见? –
不,不,我认为,至少对我来说没有。 – insanoid
你的意思是一排这样的一个例子细胞”?细胞被重复使用,所以如果你指的是一个指向特定细胞的指针,这可能对你没有任何好处。 – rdelmar
@rdelmar是的,你是对的。单元格可能已过时。所以我不能移动没有有效索引路径的单元格? –
我不是很确定你的意思是“移动细胞”。您可以通过重新排列阵列中的顺序将数据移动到任何需要的位置。那不是你想要做的吗? – rdelmar