2010-10-30 74 views
3

我正在潛入iOS開發中,並且正在玩觸摸事件。我有一個名爲UIPuzzlePiece的類,它是UIImageView的一個子類,它代表可以在屏幕上移動的拼圖塊對象。我的目標是能夠用手指在屏幕上移動拼圖塊。如何將子視圖上的觸摸事件的座標轉換爲其父視圖中的座標?

目前,我有UIPuzzlePiece類中實現的touchesBegan和touchesMoved事件......

// Handles the start of a touch 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self] anyObject]; 
    CGPoint cgLocation = [touch locationInView:self]; 
    [self setCenter:cgLocation]; 
} 

// Handles the continuation of a touch. 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self] anyObject]; 
    CGPoint cgLocation = [touch locationInView:self]; 
    [self setCenter:cgLocation]; 
} 

我現在面臨的問題是返回的CGPoint位置代表UIPuzzlePiece視圖,裏面的哪個位置是有道理的,但我需要知道在父視圖內觸摸的位置。這種方式[self setCenter:cgLocation]聲明實際上將UIPuzzlePiece移動到觸摸的位置。我總是可以寫一些黑客算法來轉換它,但我希望有一個更好或更簡單的方法來實現我的目標。如果我只有一個拼圖塊,我只是在父視圖的視圖控制器中實現觸摸事件代碼,但我有許多拼圖塊,這就是爲什麼我要在UIPuzzlePiece視圖內處理它。

您的想法? 非常感謝您的智慧!

+0

爲什麼要問'[event touchesForView:self]'而不是僅僅使用提供的'touches'參數? – 2010-10-30 22:48:10

+0

因爲我是一個noob,感謝指出! – BeachRunnerFred 2010-10-31 00:06:55

回答

4

UIView實施-convertRect:fromView:,-convertRect:toView:,-convertPoint:fromView:-convertPoint:toView:。聽起來就像你只需要使用後面的方法之一在視圖座標空間之間進行轉換。例如,如果要將CGPoint從self的座標空間轉換爲父視圖,則可以使用[self convertPoint:thePoint toView:self.superview],也可以使用[self.superview convertPoint:thePoint fromView:self](它們將執行相同的操作)。

+0

奇妙地工作,謝謝! – BeachRunnerFred 2010-10-30 22:52:34

相關問題