2014-10-28 47 views
0

我有一個簡單的演示應用程序,我試圖動態地添加一個UITeView和它後面的UIView(作爲背景)。但我每次編譯和測試移動手勢的時候,我得到這個錯誤:UIPanGestureRecognizer不接受UIView目標

- [UIView的detectPan:]:無法識別的選擇發送到實例0x17e7fc30

這裏是我的示例代碼中,我創建了UIView的和分配UIPanGesture:

CGRect textFieldFrame = CGRectMake(0, 44, 320, 44); 

// Create a TextField 
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame]; 
textField.userInteractionEnabled = NO; 
textField.layer.zPosition = 100001; 
[self.view addSubview:textField]; 

// Create the Text Background View 
UIView *textBG = [[UIView alloc] initWithFrame:textFieldFrame]; 
textBG.layer.zPosition = 100000; 
[self.view addSubview:textBG]; 

self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:textBG action:@selector(detectPan:)]; 

而且我detectPan方法:

-(void)detectPan:(UIPanGestureRecognizer *)gr { 
    NSLog(@"inside detectPan"); 
} 

有一些STE p我在執行中失蹤?我發誓,這種完全相同的方法在過去對我有效,但現在它根本不起作用。很混亂!

+0

您是否向任何控件添加了手勢? – channi 2014-10-28 13:13:46

+0

[self.view addGestureRecognizer:self.panRecognizer]; – 2014-10-28 13:22:46

回答

1

這是一個非常普遍的問題,因爲它很容易被字「目標」在-initWithTarget:action:

誤導嘗試改變initWithTarget:textBGinitWithTarget:self,事情應該工作。

因此新的代碼行應該是這樣的:

self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectPan:)]; 

人得到絆倒了字「目標」究其原因,是因爲他們認爲「目標」作爲「對象我想目標與我的自定義代碼「(即」UIView我想要拖動屏幕「),相反,他們應該考慮UIPanGestureRecognizer的目標爲」當前包含我想拖過屏幕的對象的UIView 「,換句話說」擁有我想用來計算平移手勢轉換的座標空間的UIView「

贊這樣的:

 
----------------------- 
|      | 
| Containing UIView -|-----> "THE TARGET" 
|      |  The "target" owns the x,y coordinate space where the 
| ------------  |  UIPanGestureRecognizer will calculate the movements of 
| |   |  |  your "drag" or "pan" across the screen. 
| | UIView |  | 
| | (textBG) |  | 
| |   |  | 
| ------------  | 
|      | 
----------------------- 

所以,在你的榜樣,您的應用程序崩潰,因爲你設置你的textBG爲目標,並detectPan的動作,這是essentiualy說:「當textBG對象中檢測到平移姿勢,調用textBG對象的detectPan方法「,但是在textBG對象上沒有detectPan方法,則只有textBG父級內存在的detectPan方法(即「自」)。這就是爲什麼你在這種情況下得到無法識別的選擇器發送到實例錯誤,因爲你的程序找不到與你的textBG對象關聯的-detectPan:方法。

希望這有助於!