我正在创建一个带有卡片的应用程序。在我的 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 Controller 中,它会在我触摸的任何地方被调用,但我不知道如何识别调用了哪个 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:)];
但它们都不起作用。
最佳答案
如果您向每个卡片 View 添加点击手势识别器,则可以获得对您指定的方法的回调,并且手势会连接到 View ,以便您可以直接获取对其的引用。
你的CardView
(我猜它是UIView
的子类?)有2个 subview ,它们是 ImageView :
UIImageView *_backImageView;
UIImageView *_frontImageView;
您可能需要将其中一个或两个的 userInteractionEnabled
设置为 YES
(取决于卡片何时可点击以及 subview 何时显示和隐藏)。
您还可以充当手势的委托(delegate)(如果需要,或者只是暂时调试手势是否被触发但被其他手势阻止)。
关于ios - 识别对 iOS 中以编程方式创建的 UIView 子类的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17554468/