我在自定义方法中实例化自定义类UICollectionViewCell时遇到问题。我已经有我需要的 NSIndexPath,我只需要实例化那个单元格,这样我就可以在其中放置一些进度视图......
这是我的示例代码:
-(void)setupProgressAtIndexPath:(NSIndexPath *)indexPath {
StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
_progressBackground = [[UIView alloc] initWithFrame:CGRectMake(cell.frame.size.width/6,cell.frame.size.height/6,80,80)];
else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
_progressBackground = [[UIView alloc] initWithFrame:CGRectMake(cell.frame.size.width/4,cell.frame.size.height/4,80,80)];
_progressBackground.alpha = 0.95;
_progressBackground.backgroundColor=[UIColor whiteColor];
_progressBackground.layer.cornerRadius = 20.0f;
_progressBackground.hidden=NO;
_progressView = [[M13ProgressViewPie alloc] init];
_progressView.backgroundRingWidth=2.0;
_progressView.frame = CGRectMake(0,0,64,64);
_progressView.clipsToBounds=YES;
_progressView.center = CGPointMake(40,40);
_progressView.primaryColor=[UIColor orangeColor];
_progressView.secondaryColor=[UIColor orangeColor];
[_progressBackground setHidden:YES];
[_progressBackground addSubview:_progressView];
[cell.magazineImage addSubview:_progressBackground];
}
好的,我在委托方法-collectionView中调用它:didSelectItemAtIndexPath:
只有一个问题,当我点击某个单元格时,它会将进度视图放在那里,但单元格会丢失数据并变为零。其他这一切都很好。我认为唯一的问题是这行代码:
StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
我的问题还有其他解决方案吗,有没有其他方法可以在不丢失数据的情况下实例化单元格,我需要一些答案! :)
取而代之的是:
StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
提取该索引处的现有单元格:
StoreViewCell * cell = [self.collectionView cellForItemAtIndexPath:indexPath];
即使它可能有效,我建议您_progressBackground并将_progressView相关内容放在 StoreViewCell 类中作为隐藏,然后仅在需要时取消隐藏它们
StoreViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
解释:
- cellForItemAtIndexPath:indexPath
返回零 如果单元格不可见或索引路径超出范围。这不会创建单元格,只会让您访问它们。我认为应该尽可能避免它,以防止意外泄漏和其他对表视图的干扰。
替换
StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
跟
StoreViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
要更新现有单元格 - 您不应该创建新单元格。