2010-11-13 151 views
3

所以我一直在尋找所有,我還沒有完全找到我在找什麼。觸摸CALayer時觸發一個動作?

我有一個視圖,然後是該視圖的子視圖。在第二個視圖中,我根據我給出的座標創建了CALayers。我希望能夠觸摸任何這些CALayers並觸發某些事物。

我發現不同的代碼看起來像他們可以幫助,但我一直沒有能夠實現它們。

例如:

-(void)touchesEnded:(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; 

} } } 

而且這個....

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 

    // If the touch was in the placardView, bounce it back to the center 
    if ([touch view] == placardView) { 
     // Disable user interaction so subsequent touches don't interfere with animation 
     self.userInteractionEnabled = NO; 
     [self animatePlacardViewToCenter]; 
     return; 
    }  
} 

我還是很值得初學者到這個東西。我想知道是否有人能告訴我如何做到這一點。謝謝你的幫助。

回答

13

CALayer無法直接對觸摸事件作出反應,但程序中可能有很多其他對象 - 例如託管圖層的UIView。

事件,例如觸摸屏幕時由系統生成的事件,正在通過所謂的「響應者鏈」發送。所以當觸摸屏幕時,會向位於觸摸位置的UIView發送一條消息(換句話說,稱爲方法)。觸摸有三種可能的消息:touchesBegan:withEvent:,touchesMoved:withEvent:touchesEnded:withEvent:

如果該視圖沒有實現該方法,系統會嘗試將其發送到父視圖(iOS語言的超級視圖)。它試圖將它發送到頂部視圖。如果沒有任何視圖實現該方法,它會嘗試傳遞給當前的視圖控制器,然後是父控制器,然後傳遞給應用程序對象。

這意味着您可以通過在任何這些對象中實現提及的方法來對觸摸事件作出反應。通常託管視圖或當前視圖控制器是最佳人選。

讓我們假設你在視圖中實現它。接下來的任務是找出哪些圖層已被觸摸,爲此您可以使用方便的方法convertPoint:toLayer:

例如,以下是它可能看起來像一個視圖控制器:

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    CGPoint p = [(UITouch*)[touches anyObject] locationInView:self.worldView]; 
    for (CALayer *layer in self.worldView.layer.sublayers) { 
     if ([layer containsPoint:[self.worldView.layer convertPoint:p toLayer:layer]]) { 
      // do something 
     } 
    } 
} 
+0

這條線:[self.secondView.layer convertPoint:P toLayer:pointLayer]我收到一個錯誤,指出:「不兼容類型對'containsPoint'的參數1有任何想法我應該做什麼或出了什麼問題? – 2010-11-14 19:27:54

+0

您需要確保您將CGPoint傳遞給containsPoint :.如果您不確定,請使用中間局部變量。 – 2011-12-04 17:39:34