25

我是 iPhone SDK 的新手。现在我正在使用我非常喜欢的 CALayers 进行编程——它不像 UIViews 那样昂贵,而且比 OpenGL ES sprites 的代码少得多。

我有一个问题:是否可以在 CALayer 上获得触摸事件?我了解如何在 UIView 上获得触摸事件

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 

但我找不到任何关于如何在 CALayer 对象上获得触摸事件的信息,例如,漂浮在 3D 空间中的橙色正方形。我拒绝相信我是唯一对此感到好奇的人。

我很感激任何帮助!

4

4 回答 4

31

好的-回答了我自己的问题!假设您在视图控制器的主层中有一堆 CALayers,并且您希望它们在触摸它们时变为不透明度 0.5。在视图控制器类的 .m 文件中实现此代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if ([touches count] == 1) {
        for (UITouch *touch in touches) {
            CGPoint point = [touch locationInView:[touch view]];
            point = [[touch view] convertPoint:point toView:nil];

            CALayer *layer = [(CALayer *)self.view.layer.presentationLayer hitTest:point];

            layer = layer.modelLayer;
            layer.opacity = 0.5;
        }
    }
}
于 2009-02-21T20:14:23.700 回答
8

类似于第一个答案。

- (CALayer *)layerForTouch:(UITouch *)touch {
    UIView *view = self.view;

    CGPoint location = [touch locationInView:view];
    location = [view convertPoint:location toView:nil];

    CALayer *hitPresentationLayer = [view.layer.presentationLayer hitTest:location];
    if (hitPresentationLayer) {
        return hitPresentationLayer.modelLayer;
    }

    return nil;
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CALayer *hitLayer = [self layerForTouch:touch];

    // do layer processing...
}
于 2012-08-21T06:54:13.443 回答
2

为 Swift 4 更新的Egor T答案:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
    super.touchesBegan(touches, with: event)

    if let touch = touches.first, let touchedLayer = self.layerFor(touch)
    {
        //Here you will have the layer as "touchedLayer"
    }
}

private func layerFor(_ touch: UITouch) -> CALayer?
{
    let view = self.view
    let touchLocation = touch.location(in: view)
    let locationInView = view.convert(touchLocation, to: nil)

    let hitPresentationLayer = view.layer.presentation()?.hitTest(locationInView)
    return hitPresentationLayer?.model()
}
于 2018-09-04T14:11:47.933 回答
1

我发现我得到了错误的坐标

point = [[touch view] convertPoint:point toView:nil];

我不得不把它改成

point = [[touch view] convertPoint:point toView:self.view];

获得正确的图层

于 2012-06-17T20:18:45.373 回答