Rajkumar Gurunathan
Rajkumar Gurunathan

Reputation: 271

UICollectionviewCell image change on selction

I have UICollectionview controller with UIButton in each cell. On selecting the the button I have to change the button bg image, on double-tap I have to again change it. (Single tap to like, double-tap to love concept on user interest page). What is the best way to do this?

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

    UICollectionViewCell *cell = [interestsCollection dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    UIButton* img=[[UIButton alloc]init];
    [img setImage:[UIImage imageNamed:[imgTitleArray objectAtIndex:indexPath.row]] forState:UIControlStateNormal];
    [img addTarget: self action: @selector(interestClicked:) forControlEvents: UIControlEventTouchUpInside] ;
    img.frame=CGRectMake(10, 10, 60, 60);
    [cell.contentView addSubview:img];

    UILabel* lbl=[[UILabel alloc]initWithFrame:CGRectMake(0, 75, 80, 20)];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.text=[titleArray objectAtIndex:indexPath.row];
    lbl.font = [UIFont fontWithName:@"Arial" size:11];
    lbl.textColor = [UIColor colorWithRed:135.0/255.0 green:135.0/255.0 blue:135.0/255.0 alpha:1.0];
    [cell.contentView addSubview:lbl];

    return cell;
}

Upvotes: 1

Views: 430

Answers (2)

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

Add UITapGestureRecognizer to your button and change color as you want.

  UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapOnce:)];
  UITapGestureRecognizer *tapTwice = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapTwice:)];

  tapOnce.numberOfTapsRequired = 1;
  tapTwice.numberOfTapsRequired = 2;

  //stops tapOnce from overriding tapTwice
  [tapOnce requireGestureRecognizerToFail:tapTwice];

  [self.button addGestureRecognizer:tapOnce]; //remove the other button action which calls method `button`
  [self.button addGestureRecognizer:tapTwice];

Upvotes: 0

Jatin Patel - JP
Jatin Patel - JP

Reputation: 3733

You can handle such situation with single and double TapGesture. with help of respected selector, you can change UIImage of UIButton.

Here are the link that guide you. how to create double Tap Gesture on UICollectionView. with help of this you can created single Tap gesture as well.

Collection View + Double Tap Gesture

Upvotes: 1

Related Questions