Search code examples
iosobjective-cuibuttonuicollectionviewuicollectionviewcell

IOS: UICollectionView UIButtons are not working


In my project I am using UICollectionView to display data. Data showing perfectly into UICollectionViewCells but I am also using "Edit" and "Delete" buttons in cells to edit or delete the data.

The problem occurs when I try to edit any cell and press the "edit" button. It only works for the first 3 cells. When I click on the fourth cell's edit button it displays the result of first cell on the edit page, for fifth cell it display result of second row and for 6th cell it display content of third row then for 7th row it again display result of first cell and this process continues till the end of the cells.

Edit Function

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {

        static NSString *identifier = @"cellIdentifier";
        UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

       editbtn = (UIButton *)[cell.contentView viewWithTag:206];
        editbtn.tag = indexPath.row;
        [editbtn addTarget:self action:@selector(editprocedure:) forControlEvents:UIControlEventTouchUpInside];
        [editbtn setTintColor:[UIColor blackColor]];

        deletebtn = (UIButton *)[cell.contentView viewWithTag:207];
        [deletebtn addTarget:self action:@selector(deleteprocedure:) forControlEvents:UIControlEventTouchUpInside];
        [deletebtn setTintColor:[UIColor blackColor]];
        deletebtn.tag = indexPath.row;

        return cell;
    }

i am also sharing screenshot what it looklike on simulator

enter image description here

Here is the code for edit function

-(IBAction)editprocedure:(UIButton*)sender
{
    UIButton *btnTapped = (UIButton *)sender;
    self.strdiagid = btnTapped.accessibilityIdentifier;
    NSLog(@"str ID : %@",self.strdiagid);

    self.strdiagid = [CompletephyDic objectForKey:@"id"];
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    EditProcedureVC *vch = [mainStoryboard instantiateViewControllerWithIdentifier:@"EditProcedureVC"];

    self.strdiagid = [CompletephyDic objectForKey:@"id"];
    NSString * a = self.strdiagid;
    NSLog(@"id...%@",a);

    vch.stridd = a; //stridd is the id of the procedure which is transferred to other view
    vch.infoDictionary = [dataArray objectAtIndex:sender.tag];

    [self presentViewController:vch animated:NO completion:nil];
}

Solution

  • Try this

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:YES];
    
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }