Skip to content

Instantly share code, notes, and snippets.

@satoshin2071
Last active August 29, 2015 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satoshin2071/10946102 to your computer and use it in GitHub Desktop.
Save satoshin2071/10946102 to your computer and use it in GitHub Desktop.
[ObjC][CALayer]タップされたCALayerをself.view.layer.sublayersから検知する
// self.view.layerに 画像レイヤを追加するメソッド
- (void)addMetorite:(NSTimer*)timer
{
CALayer *layer = [CALayer layer];
[layer setContents:(__bridge id)[UIImage imageNamed:@"american-flag.png"].CGImage];
[layer setContentsScale:[UIScreen mainScreen].scale];
[layer setBounds:CGRectMake(0, 0, 50, 50)];
CGRect viewBounds = CGRectInset(self.view.frame, 50, 50);
[layer setPosition:CGPointMake(arc4random_uniform(viewBounds.size.width), arc4random_uniform(viewBounds.size.height))];
[self.view.layer addSublayer:layer];
[layer startWithScaleDuration:arc4random_uniform(10)+2];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapped:)];
[self.view setGestureRecognizers:@[tap]];
}
// タップジェスチャのハンドラ
- (void)handleTapped:(UIGestureRecognizer*)gesture
{
CALayer *tappedLayer;
CGPoint touchPoint = [gesture locationInView:self.view];
NSLog(@"%@",NSStringFromCGPoint(touchPoint));
for (CALayer *layer in self.view.layer.sublayers) {
tappedLayer = [layer hitTest:touchPoint];
if (tappedLayer != nil) {
//タップされたレイヤを発見
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment