无法更新UI

时间:2013-03-12 05:28:14

标签: objective-c cocoa-touch

在我的匹配纸牌游戏中,我为新游戏创建了IBAction方法。

现在,我有一个名为updateUI的方法,可以根据操作更改UI的状态。

在我的updateUI方法中,我有一个即时呼叫alpha来消除匹配的卡片,但是当我调用newGame方法时,卡片仍然从我称为alpha的时候消失...

这是我的ViewController,请告诉我我做错了什么..谢谢! :

#import "CardGameViewController.h"
#import "PlayingCardsDeck.h"
#import "CardMatchingGame.h"


@interface CardGameViewController ()

@property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
@property (weak, nonatomic) IBOutlet UILabel *notificationLabel;
@property (weak, nonatomic) IBOutlet UILabel *scoreCounter;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;

@property (strong, nonatomic) CardMatchingGame *game;
@property (nonatomic) int flipsCount;

@end


@implementation CardGameViewController

//creating the getter method that creates a new card game.
-(CardMatchingGame *) game {

    if (!_game) _game = [[CardMatchingGame alloc] initWithCardCount:self.cardButtons.count usingDeck:[[PlayingCardsDeck alloc] init]];
    return _game;
}

//creating a setter for the IBOutletCollection cardButtons
-(void) setCardButtons:(NSArray *)cardButtons {

    _cardButtons = cardButtons;
   [self updateUI];
}


//creating the setter for the flipCount property. Whick is setting the flipsLabel to the right text and adding the number of counts.
-(void) setFlipsCount:(int)flipsCount {

    _flipsCount = flipsCount;
    self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d", self.flipsCount];

}


-(void) updateUI {

    for (UIButton *cardButton in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];
        [cardButton setTitle:card.contents forState:UIControlStateSelected];
        [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];
        cardButton.selected = card.isFaceUp;
        cardButton.enabled = !card.unplayble;
        if (card.unplayble) {
            cardButton.alpha = 0.1;
        }
        self.scoreCounter.text = [NSString stringWithFormat:@"Score: %d", self.game.score];


        if (self.game.notification) {

        self.notificationLabel.text = self.game.notification;

        }
    }
}


//Here I created a method to flipCards when the card is selected, and give the user a random card from the deck each time he flips the card. After each flip i'm incrementing the flipCount setter by one.
- (IBAction)flipCard:(UIButton *)sender {

    [self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];
    self.flipsCount++;
    [self updateUI];
}



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

    [self.game cleanHistory];

    self.flipsCount = 0;

    self.game = nil;

    [self updateUI];

}


@end

这是cleanHistory方法:

-(void)cleanHistory {

    for (Card *card in self.cards) {
        card.unplayble = NO;
        card.faceUp = NO;
    }

    self.notification = nil;
    self.score = 0;

}

1 个答案:

答案 0 :(得分:1)

确保所有对象都存在且未释放/自动释放和/或确保您在主线程中刷新UI。