我正在创建一个带有卡片的应用程序。在我的 mainViewController 中,我有以下代码:
CardView *cardView = [[CardView alloc] initWithFrame:CGRectMake(0, 0, CardWidth, CardHeight)];
cardView.card = [player.closedCards cardAtIndex:t];
[self.cardContainerView addSubview:cardView];
[cardView animateDealingToBottomPlayer:player withIndex:t withDelay:delay];
delay += 0.1f;
其中 CardView 是 UIView 的子类。每张卡片都是一个独特的 cardView,在 CardView.m 中我确实有:
@implementation CardView
{
UIImageView *_backImageView;
UIImageView *_frontImageView;
CGFloat _angle;
}
@synthesize card = _card;
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
self.backgroundColor = [UIColor clearColor];
[self loadBack];
self.userInteractionEnabled=YES;
}
return self;
}
- (void)loadBack
{
if (_backImageView == nil)
{
_backImageView = [[UIImageView alloc] initWithFrame:self.bounds];
_backImageView.image = [UIImage imageNamed:@"Back"];
_backImageView.contentMode = UIViewContentModeScaleToFill;
[self addSubview:_backImageView];
}
}
以及其他功能的实现。
由于为了赢得空间,一张牌放在其他牌的顶部(一张牌的一半是可见的,其余的被下一张牌覆盖,依此类推),我想识别每张牌上的触摸。
如果我将该代码放在 CardView 中:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Card is touched");
}
它永远不会被调用。如果我将它放在 GameView 控制器中,它会在我将触摸的任何地方被调用,但我不知道如何识别调用了哪个 cardView。你能给我一个提示吗?
编辑: 我决定使用手势。因此在我的 mainViewController 中将代码更改为:
for (PlayerPosition p = startingPlayer.position; p < startingPlayer.position + 4; ++p)
{
CardView *cardView = [[CardView alloc] initWithFrame:CGRectMake(0, 0, CardWidth, CardHeight)];
cardView.card = [player.closedCards cardAtIndex:t];
cardView.userInteractionEnabled=YES;
[self.cardContainerView addSubview:cardView];
[cardView animateDealingToBottomPlayer:player withIndex:t withDelay:delay];
delay += 0.1f;
UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cardSelected:)];
[cardView addGestureRecognizer:recognizer];
}
但这从未被调用。
-(void)cardSelected:(UITapGestureRecognizer *)recognizer
{
NSLog(@"Card Selected with gestures");
}
这是为什么?
编辑2:
我也试过添加这个:
self.cardContainerView.userInteractionEnabled=YES;
或改变这个:
UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cardSelected:)];
对此:
UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc]initWithTarget:self .cardContainerView action:@selector(cardSelected:)];
但他们都没有工作。