我在boxLayer上有一个Core Animation图像,我正在复制它,更改第2个(boxLayer2)的动作并移动它的位置,以便有人可以在第2个之间进行选择。
我希望用户能够点击boxLayer的图像,而boxLayer2图像除了boxLayer移动(除了接收触摸之外,我没有包括动画代码)外什么都不做,反之亦然。
我无法获得if语句。我已经尝试了多种变化self.layer == boxLayer或CALayer == boxlayer ...子层是一个数组,所以没有了。我知道我缺少任何帮助/解释,我们将不胜感激。

谢谢!

UIView * BounceView在VC中声明

在BounceView中,我声明了2个CALayers:boxlayer&boxlayer2

BounceView.m

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];


        // Create the new layer object
        boxLayer = [[CALayer alloc] init];
        boxLayer2 = [[CALayer alloc] init];

        // Give it a size
        [boxLayer setBounds:CGRectMake(0.0, 0.0, 185.0, 85.0)];
        [boxLayer2 setBounds:CGRectMake(0.0, 0.0, 185.0, 85.0)];

        // Give it a location
        [boxLayer setPosition:CGPointMake(150.0, 140.0)];
        [boxLayer2 setPosition:CGPointMake(150.0, 540.0)];

        // Create a UIImage
        UIImage *layerImage = [UIImage imageNamed:@"error-label.png"];
        UIImage *layerImage2 = [UIImage imageNamed:@"error-label.png"];

        // Get the underlying CGImage
        CGImageRef image = [layerImage CGImage];
        CGImageRef image2 = [layerImage2 CGImage];

        // Put the CGImage on the layer
        [boxLayer setContents:(__bridge id)image];
        [boxLayer2 setContents:(__bridge id)image2];

        // Let the image resize (without changing the aspect ratio)
        // to fill the contentRect
        [boxLayer setContentsGravity:kCAGravityResizeAspect];
        [boxLayer2 setContentsGravity:kCAGravityResizeAspect];


        // Make it a sublayer of the view's layer
        [[self layer] addSublayer:boxLayer];
        [[self layer] addSublayer:boxLayer2];

    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches
           withEvent:(UIEvent *)event
{
  if (CAlayer == boxLayer)
  {
  // do something
  }

  else
  {
  // do something else
  }
}

最佳答案

在我看来,您似乎想知道用户在触摸的内部开始触摸的那一层,而这就是您的问题。
如何找出挖掘了哪一层
CALayer有一个实例方法 - (CALayer *)hitTest:(CGPoint)thePoint

返回包含指定点的图层层次结构中接收者的最远后代(包括自身)。

因此,要找出您点击的图层,您应该执行以下操作

- (void)touchesBegan:(NSSet *)touches
           withEvent:(UIEvent *)event {
    UITouch *anyTouch = [[event allTouches] anyObject];
    CGPoint pointInView = [anyTouch locationInView:self];

    // Now you can test what layer that was tapped ...
    if ([boxLayer hitTest:pointInView]) {
        // do something with boxLayer
    }
    // the rest of your code
}
之所以有效,是因为如果该点在图层边界之外,则hitTest将返回nil

08-17 15:38