识别在iOS中以编程方式创建的UIViews子类的触摸

时间:2013-07-09 17:24:19

标签: ios uigesturerecognizer touches

我正在创建一个带卡的应用程序。在我的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];
    }
}

以及其他功能的实现。

因为为了赢得空间,一张卡放在其他卡的顶部(一张卡是可见的,其余卡被下一张卡覆盖等等),我想识别每张卡上的触摸。 / p>

如果我将该代码放在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:)];

但他们都没有工作。

1 个答案:

答案 0 :(得分:1)

如果您改为为每个卡片视图添加一个点按手势识别器,您可以回复指定的方法,并将手势连接到视图,以便您可以直接获取对它的引用。


您的CardView(我猜是UIView的子类?)有2个子视图,即图像视图:

UIImageView *_backImageView;
UIImageView *_frontImageView;

您可能希望在其中一个或两个上将userInteractionEnabled设置为YES(具体取决于卡应该可以点卡的时间以及何时显示和隐藏子视图)。

您还可以充当手势的代表(如果您需要,或者只是暂时调试手势被触发但被其他手势阻止)。