2013-01-17 49 views
2

我正在構建類似iPhone照片應用程序的應用程序。我可以使用PSUICollectionView在視圖中顯示圖像。當我點擊收集視圖的網格單元格時,應出現複選框圖像。我的問題是當我使用下面的代碼時,我看到多個隨機單元格正在填充複選框圖像。如何在uicollectionview中檢測單元格didselect委託方法

- (void)collectionView:(PSUICollectionView *)collectionView didSelectItemAtIndexPath:  (NSIndexPath *)indexPath 
{ 
    NSLog(@"%@ - %d", NSStringFromSelector(_cmd), indexPath.item); 
    ImageGridCell *cell = (ImageGridCell *)[collectionView cellForItemAtIndexPath:indexPath]; 
    UIButton *chkboxBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [chkboxBtn setFrame:CGRectMake(60, 60, 30, 30)]; 
    [chkboxBtn setImage:[UIImage imageNamed:@"Checkmark-iPhone.png"] forState:UIControlStateNormal]; 
    [cell addSubview:chkboxBtn]; 
} 
+0

任何幫助,將不勝感激。 –

回答

3

問題可能是您的自定義單元格未實現prepareForReuse方法。由於單元格被重用,它可能會或可能不會有複選框,具體取決於複選框是否添加到上次使用中。

解決這個問題的幾種方法。一種簡單的方法是將標記添加到ckhboxBtn,然後刪除prepareForReuse方法中的chkboxBton。例如,當添加的複選框,添加以下內容:

[chkboxBtn setTag:100]; 

然後在您的UICollectionViewCell類實現,添加/擴大prepareForReuse方法:

-(void)prepareForReuse{ 
    [[self viewWithTag:100] removeFromSuperview]; 
} 
+0

這是否也適用於UITableViewCells? – jhilgert00

+0

是的,它現在從其他隨機單元格刪除複選框,這是由uicollectionview重用。但問題是現在複選框甚至從選定的單元中刪除。 –

+0

@SubhenduKumarMukherjee - 您將需要跟蹤選擇了哪些單元格,並在'collectionView:cellForItemAtIndexPath:'中選中已選中的複選框。 – bobnoble

相關問題