Question

I want to be able to have it so that each time i click a button in the collection a new card is generated. For some reason this works for 2 clicks and then the title for selected state becomes nil. Thanks for your help!

 - (void) setButtonCollection:(NSMutableArray *)buttonCollection
{
_buttonCollection = buttonCollection;

for (UIButton *cardButton in self.buttonCollection){
    Card *card = [self.deck drawRandomCard];
    [cardButton setTitle:card.contents forState:UIControlStateSelected];

  }

}

- (IBAction) flipCard:(UIButton *)sender {

sender.selected = !sender.isSelected;
[self setButtonCollection: self.buttonCollection];
}
Was it helpful?

Solution

If i am not mistaken you are working on CS193P. With every click you are going through the for loop which is redrawing cards for every button in the collection. You probably have only 52 cards in the deck and after two clicks there are not more cards so [self.deck drawRandomCard] is returning nil which sets title to nil. You do not have to set all the cards in the setter of the collection you can just set each card in the flipCard when it is flipped. This is my version of the flipCard. It also checks if there are no more cards. Let me know if this what you were looking for.

- (IBAction)flipCard:(UIButton *)sender {

    sender.selected = !sender.selected;
    if (sender.selected) {
        PlayingCard *randomCard = [self.deck drawRandomCard];
        if (!randomCard) {
            //will alert user no more cards, disable the button and set alpha to 0.3
            sender.enabled = NO;
            sender.alpha = 0.3;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No More Cards" message:@"Game Over" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }else{
            [sender setTitle:randomCard.contents forState:UIControlStateSelected];
        }
    }
    self.flipCount++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top