MVC模式在iOS App 开发中的应用 - Controller

2 篇文章 0 订阅

//

//  ViewController.h

//  TonyGame


#import <UIKit/UIKit.h>

#import "Deck.h"


@interface ViewController : UIViewController



//protecred for subclass

- (Deck *)createDeck; //abstract


@end


//

//  ViewController.m

//  TonyGame


#import "ViewController.h"

#import "PlayingCardDeck.h"

#import "CardMatchingGame.h"


@interface ViewController ()

@property (nonatomic, strong) Deck *deck;

@property (nonatomic, strong) CardMatchingGame *game;

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;

@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;


@end


@implementation ViewController


- (CardMatchingGame *)game

{

    if (!_game) _game = [[CardMatchingGame alloc] initWithCardCount:[self.cardButtons count] usingDeck:[self createDeck]];

    return _game;

}


- (Deck *) deck

{

    if (!_deck) _deck = [self createDeck];

    return _deck;

}


- (Deck *) createDeck //abstract

{

    //return [[PlayingCardDeck alloc] init];

    return nil;

}



- (IBAction)touchCardButton:(UIButton *)sender

{

    

    int cardIndex = [self.cardButtons indexOfObject:sender];

    [self.game chooseCardAtIndex:cardIndex];

    [self updateUI];

    

}


- (void) updateUI

{

    for (UIButton *cardButton in self.cardButtons) {

        int cardIndex = [self.cardButtons indexOfObject:cardButton];

        Card *card = [self.game cardAtIndex:cardIndex];

        [cardButton setTitle:[self titleForCard:card] forState:UIControlStateNormal];

        [cardButton setBackgroundImage:[self backgroundImageForCard:card] forState:UIControlStateNormal];

        cardButton.enabled = !card.isMatched;

    }

    self.scoreLabel.text = [NSString stringWithFormat:@"Score: %d", self.game.score];

}


- (NSString *)titleForCard:(Card *)card

{

    return card.isChosen ? card.contents : @"";

}


- (UIImage *)backgroundImageForCard:(Card *)card

{

    return [UIImage imageNamed:card.isChosen ? @"cardfront" : @"cardback"];

}


@end


//

//  PlayingCardGameViewController.h

//  TonyGame


#import "ViewController.h"


@interface PlayingCardGameViewController : ViewController


@end


//

//  PlayingCardGameViewController.m

//  TonyGame

//


#import "PlayingCardGameViewController.h"

#import "PlayingCardDeck.h"



@interface PlayingCardGameViewController()


@end


@implementation PlayingCardGameViewController


- (Deck *)createDeck

{

    return [[PlayingCardDeck alloc] init];

}


@end




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值