首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用UISwitch告诉控制器检查方法中的某个条件

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

Stack Overflow用户
提问于 2013-03-15 01:45:55
回答 2查看 400关注 0票数 0

在我的卡片匹配游戏中:

-I有一种方法,可以检查在特定索引中翻过的牌。这基本上就是应用程序中的全部逻辑。

-I有另一个检查匹配的方法。

现在,我在视图控制器中创建了一个切换按钮,它将告诉控制器用户更改了"3“卡的模式,而不是基本模式(2张卡)。

我的问题是,如果有两个以上的匹配,我该如何告诉控制器检查匹配方法。这让我抓狂,请试着帮我弄清楚这个问题。

我在控制器中也有一个updateUI方法,它使匹配的卡片淡出,所以我需要确保它的行为是相同的。

下面的代码以相同的顺序展示了flipCardAtIndex方法,匹配方法和视图控制器:

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

代码语言:javascript
运行
复制
#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 (只有第一种方法,匹配方法):

代码语言:javascript
运行
复制
#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;

}

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

代码语言:javascript
运行
复制
#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
EN

回答 2

Stack Overflow用户

发布于 2013-03-15 02:29:47

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

代码语言:javascript
运行
复制
[mySwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];

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

代码语言:javascript
运行
复制
- (void)switchValueChange:(id)sender
  {
      UISwitch *switch = (UISwitch *) sender;
      if (sender.on)
        self.mode = 2;
      else
        self.mode = 3;
  }

如果我的假设是正确的,那么“模式”是指要匹配多少张牌,对吗?2的意思是,2张牌正面朝上时应该是相同的,3意味着3张牌应该在花色或数字上匹配。

首先,将PlayingCards中的match方法更改为如下所示(接受另一个名为mode的参数)(您可能还需要在其父类中更新相同的方法):

代码语言:javascript
运行
复制
//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的参数):

代码语言:javascript
运行
复制
-(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;   
    }
}

最后,将调用更改为

代码语言:javascript
运行
复制
[self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];

在……里面

代码语言:javascript
运行
复制
- (IBAction)flipCard:(UIButton *)sender 

CardGameViewController to的方法

代码语言:javascript
运行
复制
[self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender] forMode:self.mode];

看一看这是否有意义。

票数 0
EN

Stack Overflow用户

发布于 2013-03-15 15:22:59

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

代码语言:javascript
运行
复制
@synthesize mySwitch = _mySwitch;

现在,将您的viewDidLoad方法更改为:

代码语言:javascript
运行
复制
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.mySwitch addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
    [self updateUI];

}

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

现在试一试吧。您知道如何在xcode中使用断点进行调试吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15416536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档