如何在CollectionView委托方法之外实例化自定义类UICollectionViewCell?

时间:2016-01-25 09:22:13

标签: ios objective-c uicollectionview

我在自定义方法中实例化自定义类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];

我的问题是否还有其他解决办法,有没有其他方法来实例化单元格而不会丢失数据,我需要一些答案! :)

3 个答案:

答案 0 :(得分:2)

而不是:

StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

提取该索引处的现有单元格:

StoreViewCell * cell = [self.collectionView cellForItemAtIndexPath:indexPath];

即使它可能有效,我建议你将StoreViewCell类中的_progressBackground和_progressView相关内容隐藏起来,然后只在你需要时取消隐藏它们

答案 1 :(得分:2)

StoreViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];

说明:

- cellForItemAtIndexPath:indexPath返回nil  如果单元格不可见或索引路径超出范围。这不会创建单元格,只允许您访问它们。我认为应该尽可能地避免意外泄漏和对tableView的其他干扰。

答案 2 :(得分:1)

替换

StoreViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

 StoreViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];

要让现有单元格更新 - 您不应该创建新单元格。

相关问题