如果为 Cell 分配了标签号,我该如何跟踪?我将创建 10 - 90 个单元格。但是,当我上下滚动(在 View 内和 View 外)时,重新创建单元格后,单元格标记号继续增加。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSManagedObject *managedObject = rowModels[indexPath.row];
NSString *entityName= [[managedObject entity]name];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %i", entityName, [indexPath row]];
cell.tag = cellTagIndex++;
NSString *tagString = [NSString stringWithFormat:@"%d", cell.tag];
//cellToObjectMap is NSMutableDictionary
if ([entityName isEqualToString:@"Test1" ])
{
[cellToObjectMap setValue:[managedObject valueForKey:@"test1_id"] forKey:tagString];
}
else if ([entityName isEqualToString:@"Test2t" ])
{
[cellToObjectMap setValue:[managedObject valueForKey:@"test2_id"] forKey:tagString];
}
NSLog(@"Cell.tag %@ Value: %@", tagString, [cellToObjectMap objectForKey:tagString]);
return cell;
}
日志:
2013-08-15 19:07:57.243 Time[8510:c07] Cell.tag 0 Value: 95AB73F8-E0C2-4D17-B6BE-9FC2E696959D
2013-08-15 19:07:57.244 Time[8510:c07] Cell.tag 1 Value: EA163C15-0CF1-4275-B939-0ED9F62C240D
2013-08-15 19:07:57.245 Time[8510:c07] Cell.tag 2 Value: DDFD36F6-4CAD-4C26-A38C-B22D827199BD
2013-08-15 19:07:57.245 Time[8510:c07] Cell.tag 3 Value: AC9FD255-08CF-44C4-B168-E6441D08AC54
2013-08-15 19:07:57.246 Time[8510:c07] Cell.tag 4 Value: 48C2DE0C-88C3-48CC-BBB1-350088EE9862
2013-08-15 19:07:57.247 Time[8510:c07] Cell.tag 5 Value: 5C4495A1-FF3D-439E-BD01-88312EF881AD
........
........ // Cell.tag continues to increase as I scroll up and down the screen.
2013-08-15 19:10:38.903 Time[8510:c07] Cell.tag 254 Value: 81CAA228-51F4-464C-8B2B-12D2A66C3BA8
2013-08-15 19:10:38.969 Time[8510:c07] Cell.tag 255 Value: 7DC03657-B987-4994-8066-5393F77D891B
2013-08-15 19:10:39.052 Time[8510:c07] Cell.tag 256 Value: BB1BCFD2-FBD9-46FA-B662-56085254FD46
2013-08-15 19:10:39.169 Time[8510:c07] Cell.tag 257 Value: 0C78EBE0-AD83-4A21-8546-37EA17EAB5CA
如果一个单元格编号已经分配了一个 cell.tag,我该如何跟踪,如果已经分配了,我如何确定字典是否有现有的键?
最佳答案
您只需要为每个新单元分配一个标签,对吗?
像这样定义一个静态标签
#define CELL_TAG 100000
现在在你的 cellForRowAtIndexPath 中
cell.tag = indexPath.row + CELL_TAG
您添加的后缀表达式将始终增加标记,因此也将其删除。
附言。单元格初始化在哪里?如果你需要的话
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
关于iOS:UITableView cell.tag 数在进出 View 时不断增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18264866/