Search code examples
iosuicollectionviewnsindexpath

UICollectionView move specific cell


I have a working sample of UICollectionView, I can move a cell [by indexPath], but I need a specific cell [indexpath.row?] So I move the cell i need, At the moment a cell moves but not the correct one, so when I move for example

NSIndexPath *index = [indexPaths objectAtIndex:0];

the cell on indexpath.row = 3 moves, how to call the cell by indexpath row?

enter image description here

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor lightGrayColor];

    CGRect frame = CGRectMake(10, 100, 300, 500);

    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    self.collectionView=[[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [self.collectionView setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:self.collectionView];


    UIButton *animus = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    animus.frame = CGRectMake(100, 20, 90, 30);
    [animus setTitle:@"Animus" forState:UIControlStateNormal];
    [animus addTarget:self action:@selector(animusPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:animus];

}

- (void)animusPressed:(id)sender
{
    NSIndexPath *index = [indexPaths objectAtIndex:0]; //en el index!

 NSLog(@"moving tha cell :: %d", index.row);


    __weak UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:index]; // Avoid retain cycles

    CGRect frame = cell.frame;

    frame.origin.y = 300;

    cell.frame = frame;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];

    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
    [cell.contentView addSubview:title];
    NSString *titleLbl = [NSString stringWithFormat:@"i = %d", indexPath.row];
    title.text = titleLbl;

    return cell;
}

So a cell moves, but not the one I want, I need to move a specific cell, by indexpath.row like it is shown on the cellForRow,

How to specify what cell I want to move?

Please note im moving cell on index = 0 , but the indexpath.row = 2 is the one moving

Thanks


Solution

  • Have you tried something like this?

    [NSIndexPath indexPathForItem:0 inSection:0]