如何使用UISwitch告诉控制器检查方法中的某个条件

时间:2013-03-14 17:45:55

标签: iphone ios objective-c cocoa-touch cocoa

在我的卡片匹配游戏中:

- 我有一种检查在特定索引中翻转的卡片的方法。它基本上是应用程序中的整个逻辑。

- 我有另一种检查匹配的方法。

现在,我在视图控制器中创建了一个开关按钮,告诉控制器用户改变了“3”卡而不是基本模式(2张卡)的模式。

我的问题是,如果有超过2场比赛,我如何告诉控制器检查匹配方法..这让我发疯了请尝试帮助我解决这个问题。

我在控制器中也有一个updateUI方法,可以使匹配的卡逐渐消失,所以我需要确保它的行为相同。

以下代码显示了flipCardAtIndex方法,匹配方法&以相同的顺序查看控制器:

CardMatchingGame.m(最后一个方法是flipCardAtIndex):

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

@interface CardMatchingGame()

@property (readwrite, nonatomic) int score;
@property (strong, nonatomic) NSMutableArray *cards;
@property (strong, nonatomic) NSString *notification;
@end        


@implementation CardMatchingGame


-(NSMutableArray *) cards {

    if (!_cards) _cards = [[NSMutableArray alloc] init];
    return _cards;
}


-(id)initWithCardCount:(NSUInteger)count usingDeck:(Deck *)deck {

    self = [super init];

    if (self) {

        for (int i = 0; i < count; i++) {
            Card *card = [deck drawRandonCard];

            if (!card) {
                self = nil;
            } else {
                self.cards[i] = card;
            }
        }
    }
    return self;
}

-(Card *) cardAtIndex:(NSUInteger)index {

    return (index < self.cards.count) ? self.cards[index] : nil;
}

#define FLIP_COST 1
#define MISMATCH_PENALTY 2
#define BONUS 4

-(void) flipCardAtIndex:(NSUInteger)index {



    Card *card = [self cardAtIndex:index];

    if (!card.isUnplayable) {

        if (!card.isFaceUp) {

            for (Card *otherCard in self.cards) {

                if (otherCard.isFaceUp && !otherCard.isUnplayable) {

                    NSMutableArray *myCards = [[NSMutableArray alloc] init];

                    [myCards addObject:otherCard];

                    int matchScore = [card match:myCards];

                    if (matchScore) {

                        otherCard.unplayble = YES;
                        card.unplayble = YES;

                        self.notification = [NSString stringWithFormat:@"%@ & %@  match!", card.contents, otherCard.contents];

                        self.score += matchScore * BONUS;
                    } else {
                        otherCard.faceUp = NO;
                        self.score -= MISMATCH_PENALTY;
                        self.notification = [NSString stringWithFormat:@"%@ did not matched to %@", card.contents, otherCard.contents];
                    }
                    break;
                }

            }
            self.score -= FLIP_COST;
        }
        card.faceUp = !card.isFaceUp;   
    }
}
@end

PlayingCards.m(仅限第一种方法,匹配方法):

#import "PlayingCards.h"


@implementation PlayingCards

@synthesize suit = _suit;

//overriding the :match method of cards to give different acore if its only a suit match or a number match
-(int)match:(NSArray *)cardToMatch {

    int score = 0;

    for (int i = 0; i < cardToMatch.count; i++) {

        PlayingCards *nextCard = cardToMatch[i];
        if ([nextCard.suit isEqualToString:self.suit]) {

            score += 1;
        } else if (nextCard.rank == self.rank) {

            score += 4;
        }
    }

   return score;

}

我的视图控制器(最后一种方法是切换按钮的方法):

#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;

@property (nonatomic) NSNumber *mode;
//@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;
@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;

@end


@implementation CardGameViewController

@synthesize mode = _mode;

//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;
        }

        //updating the score 
        self.scoreCounter.text = [NSString stringWithFormat:@"Score: %d", self.game.score];

        //if notification in CardMatchingGame.m is no nil, it will be presented 
        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] forMode:self.mode];
    self.flipsCount++;
    [self updateUI];
}

//sending an alert if the user clicked on new game button
- (IBAction)newGame:(UIButton *)sender {

   UIAlertView* mes=[[UIAlertView alloc] initWithTitle:@"Are you sure..?" message:@"This will start a new game" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];

    [mes show];

}

//preforming an action according to the user choice for the alert yes/no to start a new game
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if (buttonIndex != [alertView cancelButtonIndex]) {

        self.flipsCount = 0;
        self.game = nil;
        for (UIButton *button in self.cardButtons) {
            Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
            card.unplayble = NO;
            card.faceUp = NO;
            button.alpha = 1;
        }

        self.notificationLabel.text = nil;
        [self updateUI];

    }
}

-(void) setMode:(NSNumber *)mode {

    mode = _mode;
}

-(void) switchValueChange:(id)sender {

    UISwitch *Switch = (UISwitch *) sender;

    NSNumber *twoCards = [NSNumber numberWithInt:2];
    NSNumber *threeCards = [NSNumber numberWithInt:3];


    if (Switch.on) {
        self.mode = twoCards;
    }
    else
    {
        self.mode = threeCards;
    }
}


- (void)viewDidLoad
{
    UISwitch *mySwitch;
    [super viewDidLoad];
    [mySwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
    [self updateUI];

}

@end

2 个答案:

答案 0 :(得分:0)

实际上,获取开关值很容易。您可以设置从交换机到viewController(CardGameViewController)的引用插座,并在视图控制器的viewDidLoad方法中添加方法以侦听对switch值的更改:

[mySwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];

在CardGameViewController中添加一个名为NSNumber *mode的新属性并进行综合。 现在你可以在switchValueChanged方法中更新“模式”(我认为可能是一个实例变量):

- (void)switchValueChange:(id)sender
  {
      UISwitch *switch = (UISwitch *) sender;
      if (sender.on)
        self.mode = 2;
      else
        self.mode = 3;
  }

如果我的假设是正确的,那么通过“模式”你的意思是要匹配多少张牌,这是正确的吗? 2表示,面对面时,2张牌应该是相同的,3表示3张牌应该是套装或号码匹配。

首先将您的PlayingCards中的匹配方法更改为此类(接受另一个名为mode的参数)(您可能还必须在其父类中更新相同的方法):

//overriding the :match method of cards to give different acore if its only a suit match or a number match
-(int)match:(NSArray *)cardToMatch forMode:(NSNumber *) mode{

    int score = 0;
    int cardsMatched = 0;

    for (int i = 0; i < cardToMatch.count; i++) {

        PlayingCards *nextCard = cardToMatch[i];
        if ([nextCard.suit isEqualToString:self.suit]) {

            score += 1;
            cardsMatched++;
        } else if (nextCard.rank == self.rank) {

            score += 4;
            cardsMatched++;
        }

        if (cardsMatched >= [mode intValue])
          break;

    }

   return score;

}

现在,在您的CardMatchingGame.m方法中,将flipCardAtIndex方法更改为此(接受另一个名为mode的参数):

-(void) flipCardAtIndex:(NSUInteger)index forMode (NSNumber *mode) {

    Card *card = [self cardAtIndex:index];

    if (!card.isUnplayable) {

        if (!card.isFaceUp) {

            NSMutableArray *myFaceUpCards = [[NSMutableArray alloc] init];



            // UPDATED: Loop through all the cards that are faced up and add them to an array first
            for (Card *otherCard in self.cards) {

                if (otherCard.isFaceUp && !otherCard.isUnplayable && orderCard != card) {

                    [myCards addObject:otherCard];
             }

             // UPDATED: Now call the method to do the match. The match method now takes an extra parameter
                    int matchScore = [card match:myCards forMode:mode];



                    if (matchScore) {

                        otherCard.unplayble = YES;
                        card.unplayble = YES;

                        self.notification = [NSString stringWithFormat:@"%@ & %@  match!", card.contents, otherCard.contents];

                        self.score += matchScore * BONUS;
                    } else {
                        otherCard.faceUp = NO;
                        self.score -= MISMATCH_PENALTY;
                        self.notification = [NSString stringWithFormat:@"%@ did not matched to %@", card.contents, otherCard.contents];
                    }

            }
            self.score -= FLIP_COST;
        }
        card.faceUp = !card.isFaceUp;   
    }
}

最后,将呼叫改为

[self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];

- (IBAction)flipCard:(UIButton *)sender 

CardGameViewController的方法

[self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender] forMode:self.mode];

看看是否有意义。

答案 1 :(得分:0)

从.m类中删除@property (weak, nonatomic) IBOutlet UISwitch *mySwitch;。 相反,转到故事板,单击带有开关的控制器,然后单击右上方的“助理编辑器”按钮(看起来像一张脸)。它将打开CardGameViewController.h。现在右键单击storyoard上的开关视图,然后单击并从New Referencing Outlet拖动到CardViewController.h。这是您将开关引用到控制器的方式。 现在您在接口文件中有switch变量,转到您的实现文件(CardGameViewController.m)并合成变量:

@synthesize mySwitch = _mySwitch;

现在,将viewDidLoad方法更改为:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.mySwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
    [self updateUI];

}

还删除setMode方法。如果你正在合成模式变量,那么你不需要它。

立即试一试。你知道如何使用断点在xcode中调试吗?