I am new for IOS development , and I try to use UIcollectionView
to show the photo without using storyboard
.
I create a xib file
call AITFileCell_grid.xib
, and add a Collection View Cell
.
I also create another xib file
and add the Collection View
for loading Collection View Cell
.
I want to selected multiple file and delete them by delete button
.
But I can not get the cell when I click the delete button
by following code.
if(self.collectionView.indexPathsForSelectedItems > 0){
NSLog(@"indexPathsForSelectedItems...count.%@..@@@" , self.collectionView.indexPathsForSelectedItems);
for(NSIndexPath *indexPath in self.collectionView.indexPathsForSelectedItems){
// [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", directory, [fileList objectAtIndex:indexPath.row]];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil] ;
AITFileCell_grid *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"AITFileCell_grid" forIndexPath:indexPath];
}
}
But the sell seems not correct...
How to get the selected cell
in collectionView
?
Usually your delete button should have a selector like this:
deleteButton = [[UIButton alloc] init];
...
[deleteButton addTarget:self selector:@sel(buttonPressed:) forControlEvent:UIControlEventTouchUpInside];
I believe you can get the indexPath using the following:
-(void)buttonPressed:(id)sender
{
UIButton *button = (UIButton *)sender;
CGPoint rootPoint = [button convertPoint:CGPointZero toView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:rootPoint];
// -----------------------------------------------------------------
// Now you have your indexPath, you can delete your item
// -----------------------------------------------------------------
// first update your data source, in this case, I assume your data source
// is a list of values stored inside a NSArray
NSMutableArray *updatedList = [self.myListData mutableCopy];
[updatedList removeObjectAtIndex:indexPath.row];
self.myListData = updatedList;
// now update your interface
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPath:@[indexPath]];
}];
}
For checking which Collection Cell is clicked, you can use this delegate method in your Controller.
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
int itemNo = (int)[indexPath row]+1;
CollectionCell *selectedCell =(CollectionCell*)[collectionView cellForItemAtIndexPath:indexPath];
switch (itemNo) {
case 1:
{
//your Logic for 1st Cell
break;
}
case 2:
{
//your Logic for 2nd Cell
break;
}
.
.
.
}
}