如何在CALayer上获得触摸事件?

问题描述 投票:21回答:4

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

我有这个问题:是否有可能在CALayer上获得触摸事件?我知道如何在UIView上获得触摸事件

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

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

我感谢任何帮助!

iphone events touch calayer
4个回答
29
投票

好的 - 回答了我自己的问题!假设您在视图控制器的主图层中有一堆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;
        }
    }
}

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...
}

1
投票

我发现我的坐标错误

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

我不得不改变它

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

获得正确的图层


0
投票

Egor T answer针对Swift 4进行了更新:

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()
}
© www.soinside.com 2019 - 2024. All rights reserved.