ios 编程新手,所以为了练习,我正在尝试制作一个带有扑克牌的简单应用程序,它回到视图上,您可以点击它以显示卡片的正面。每次点击卡片的正面都会有所不同。我想要实现的是,当我点击卡片时:
- 它翻转并显示一张随机卡片,
- 每次翻转卡片时,标签都会增加 1
我完成了第二个要求,但我似乎无法正确完成第一个要求。我有 3 个模型(卡片、甲板、扑克牌) 我的甲板模型负责随机化卡片,这里是代码。
甲板.h
#import <Foundation/Foundation.h>
#import "Card.h"
@interface Deck : NSObject
- (void)addCard:(Card *)card atTop:(BOOL)atTop;
- (Card *)drawRandomCard;
@end
甲板.m
#import "Deck.h"
@interface Deck()
@property (strong, nonatomic) NSMutableArray *cards;
@end
@implementation Deck
-(NSMutableArray *)cards
{
if(!_cards) _cards =[[NSMutableArray alloc] init];
return _cards;
}
- (void)addCard:(Card *)card atTop:(BOOL)atTop
{
if(card){
if(atTop){
[self.cards insertObject:card atIndex:0];
}
else
{
[self.cards addObject:card];
}
}
}
- (Card *)drawRandomCard
{
Card *randomCard = nil;
if(self.cards.count){
unsigned index = arc4random() % self.cards.count;
randomCard = self.cards[index];
[self.cards removeObjectAtIndex:index];
}
return randomCard;
}
@end
My PlayingCard 基本上描述了卡片的内容。例如。红心杰克,方块 2,其中杰克是卡片的“等级”,“红心”是卡片的花色,它们共同构成卡片的内容。
扑克牌.h
#import <Foundation/Foundation.h>
#import "Card.h"
@interface PlayingCard : NSObject
@property (strong, nonatomic) NSString *suit;
@property (nonatomic) NSUInteger rank;
+ (NSArray *) validSuits;
+ (NSUInteger) maxRank;
- (NSString *)contents;
@end
扑克牌.m
#import "PlayingCard.h"
@implementation PlayingCard
- (NSString *)contents
{
NSArray *rankStrings = [PlayingCard rankStrings];
return [rankStrings[self.rank] stringByAppendingString:self.suit];
}
@synthesize suit = _suit;
+(NSArray *)validSuits{
return @[@"♥", @"♦", @"♠", @"♣"] ;
}
+(NSArray *)rankStrings{
return @[@ "?", @"A", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9",@"10", @"J", @"Q", @"K"];
}
-(void)setSuit:(NSString *)suit
{
if([[PlayingCard validSuits] containsObject:suit]){
_suit = suit;
}
}
-(NSString *)suit{
return _suit ? _suit: @"?";
}
+ (NSUInteger)maxRank {
return [self rankStrings].count-1;
}
-(void)setRank:(NSUInteger)rank{
if(rank <= [PlayingCard maxRank]) {
_rank = rank;
}
}
@end
最后是我的 ViewController.m
#import "CardGameViewController.h"
#import "Card.h"
#import "Deck.h"
#import "PlayingCard.h"
@interface CardGameViewController ()
@property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
@property (nonatomic) int flipCount;
@property (nonatomic) NSString *title;
@property (weak, nonatomic) IBOutlet UIButton *cardRandom;
@end
@implementation CardGameViewController
- (void)setFlipCount:(int)flipCount
{
_flipCount = flipCount;
self.flipsLabel.text = [NSString stringWithFormat:@" Flips:%d", self.flipCount ];
}
- (IBAction)flipCard:(UIButton *)sender
{
if(sender.isSelected) {
sender.selected = NO;
self.flipCount ++;
}
else{
sender.selected = YES;
self.flipCount ++;
}
}
@end
我对此进行了研究,发现我可能应该使用
- (void)setTitle:(NSString *)title forState:(UIControlState)state
其中状态将是 UIControlStateSelected 因为包含内容的卡片正面是按钮的选定内容但我不知道如何根据我的模型开发的随机卡片内容设置标题。