我是iPhone SDK的新手.现在我正在使用CALayers进行编程,我非常喜欢它 - 不像UIViews那么昂贵,而且代码比OpenGL ES sprites少得多.
我有这个问题:是否有可能在CALayer上获得触摸事件?我知道如何在UIView上获得触摸事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
但我无法找到关于如何在CALayer对象上获取触摸事件的任何地方,例如,漂浮在3D空间中的橙色方块.我拒绝相信我是唯一一个对此感到好奇的人.
我感谢任何帮助!
好的 - 回答了我自己的问题!假设您在视图控制器的主图层中有一堆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; } } }
与第一个答案类似.
- (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... }