[英]iOS: how can I assign each of my cells a tag in this method?
我需要使用標簽ID更新每個單元格。 我已經完成了此操作,但是有一個關鍵缺陷。 當我更改單元格的順序時,這些單元格將繼承錯誤的ID。例如,如果我將單元格2交換為單元格1,則單元格1將獲得單元格2 ID,而單元格2將獲得單元格1 ID。 每個ID只需要用於一個特定的單元格和一個單元格,這樣,如果我更改了包含其ID的單元格的順序,就可以這樣做。 我相信問題是我在UICollectionView委托中調用id,因此每次更新時,它將從服務器調用並再次重用id。 我該如何解決?
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.collectionView registerClass:[Cell class] forCellWithReuseIdentifier:@"Cell"];
Cell *cell = (Cell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if (self.data == nil || [self.data count] == 0) {
self.data = [sections objectAtIndex:indexPath.section];
cell.cellImg.image = nil;
[tagArray removeAllObjects];
} else {
self.data = [sections objectAtIndex:indexPath.section];
cell.cellImg.image = [self.data objectAtIndex:indexPath.item];
self.largeImage.image = [self.data objectAtIndex:0];
NSDictionary *url = [self.result objectAtIndex:indexPath.row];
NSString *string = [url valueForKey:@"id"];
cell.cellImg.tag = string.intValue;
[tagArray addObject:[NSNumber numberWithInt:cell.cellImg.tag]];
}
return cell;
}
-(void)didGetResults:(NSArray *)resultArray
{
self.resultArray = resultArray;
resultModel = [self.resultArray objectAtIndex:0];
self.resultdata = resultModel.resultdata;
sections = [[NSMutableArray alloc] initWithCapacity:SECTION_COUNT];
for(int s = 0; s < SECTION_COUNT; s++) {
self.data = [[NSMutableArray alloc] initWithCapacity:self.resultdata.count];
for(int i = 0; i < self.result.count; i++) {
NSDictionary *url = [self.result objectAtIndex:i];
NSString *string = [url valueForKey:@"web_path"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:string]]]];
[self.data addObject:myImageView.image];
}
[sections addObject:self.data];
}
[tagArray removeAllObjects];
[self.collectionView reloadData];
}
您可以做的是先讀取單元格ID,然后查看該標簽ID是否與列表中的ID相匹配。 如果不是,則為其分配一個ID(通常假定該特定單元格或整個表視圖的首次加載)。 如果是這樣,請勿分配新值。 我知道如果您的可分配ID值在表格視圖范圍內,則此方法不是特別安全。 在這種情況下,請使用散列或較大編號的id或一個由填充整數(例如id[1] = 1001
和id[2] = 1002
)組成的串聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.