Sakthi Sakthi - 1 year ago 51
Objective-C Question

How can i pass my id from UICollectionView

i want to store my recipe id as session id when i click the button inside

. Can anyone give me solution for this. i set tag value as my recipe id but i am not sure this is correct way.

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

[self.mySpinner stopAnimating];

static NSString *identifier = @"Cell";

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

UIButton *recipeid= (UIButton *)[cell.contentView viewWithTag:107];

[recipeid addTarget:self
action:@selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[recipeid setTag:(int)[[array objectAtIndex:indexPath.row] valueForKey:@"RecID"]];


-(IBAction)aMethod:(UIButton *)sender

[[NSUserDefaults standardUserDefaults] setObject:sender forKey:[NSNumber numberWithInt:(@"RecipeIdsession",sender.tag)]];

[[NSUserDefaults standardUserDefaults] synchronize];
[self performSegueWithIdentifier:@"recipedetail" sender:nil];

Answer Source

You can use the CGPoint of your Button to get the IndexPath like this.

-(void)aMethod:(UIButton *)sender{
    CGPoint center=; 
    CGPoint point = [sender.superview convertPoint:center toView:self.collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    NSInteger recid = [[array objectAtIndex:indexPath.row] valueForKey:@"RecID"];

Note: Remove that setTag line from the cellForItemAtIndexPath no need to set the Tag.