Question

I have a custom UICollectionViewCell that holds a UIButton with an image set. The purpose of this bottom is to allow users who are shopping via the app to add items to a list of their favourite items.

I have 2 versions of the image. One is a default greyed out heart and the other is a black heart. When a user taps to add an item to their favourites this method is fired:

Method fired on tap of heart:

- (void)addToFavouritesButtonTapped
{
    NSLog(@"add to favourites button tapped");
}

In my cellForItemAtIndexPath method for my UICollectionView I have this:

    _addToFavouritesButton = [cell addFavouriteButton];
   [_addToFavouritesButton addTarget:_thisController action:@selector(addToFavouritesButtonTapped) forControlEvents:UIControlEventTouchUpInside];

Upon tapping the heart to save an item to favourites I'd like the image to change to my highlighted version which is the black heart.

How can I achieve this?

Was it helpful?

Solution

Set the other image as the one for the UIControlStateSelected and then when the button is tapped set the button to selected= YES, this will then change the image.

_addToFavouritesButton = [cell addFavouriteButton];   
[_addToFavouritesButton addTarget:_thisController action:@selector(addToFavouritesButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_addToFavouritesButton setImage:blackHeart forState:UIControlStateSelected];

- (void)addToFavouritesButtonTapped:(UIButton *)sender
{
    NSLog(@"add to favourites button tapped");
    sender.selected = YES;
}

OTHER TIPS

You can use the button state to show a different image. Check the documentation for UIButton, there is a method setImage:forState: that you can use to set an image for normal state, highlighted state, selected state. You can even do it in Interface Builder.

On a side note, if you want to do something else with the button once it's pressed you should do the following:

Append : to the selector

[_addToFavouritesButton addTarget:_thisController action:@selector(addToFavouritesButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

Receive the UIButton in the method

- (void)addToFavouritesButtonTapped:(UIButton *)sender

Then you can manipulate the button in that method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top