2011-03-09 52 views
0

我有一個UIButton發送所述draginside事件:的UIButton崩潰上uitouch事件

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

它通過在viewDidLoad中以下代碼:

[colourButton1 addTarget:self action:@selector(touchesBegan:withEvent:) forControlEvents:UIControlEventTouchDown]; 

在其內將其發送到方法,有以下行:

UITouch *myTouch = [touches anyObject]; 

而由於某種原因,當在UIButton內拖動時,這種崩潰應用程序。任何想法爲什麼?

編輯:解..

-(IBAction)buttonDragged:(id)button withEvent:(UIEvent*)event { 
    NSSet *touches = [event touchesForView:colourButton1]; 
    [self touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event]; 
} 

回答

4

當你把目標來控制你可以通過3種選擇的行動 -

- (void)action 
- (void)action:(id)sender 
- (void)action:(id)sender withEvent:(UIEvent*)event 

名稱並不重要,它的數的重要參數。如果控件發送它的目標是帶有2個參數的消息,那麼第一個參數將自己控制(在您的情況下爲UIButton的實例),第二個參數爲UIEvent的實例。但你期望NSSet的實例作爲第一個參數,併發送一條消息anyObject,其中UIButton不理解。這是崩潰的原因。

你爲什麼要嘗試從UI控件發送事件到首先觸摸處理方法touchesMoved:withEvent:?它可能會做一些不同於你的意思的東西。

UPDATE:

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event { 
    UITouch *t = [touches anyObject]; 
    CGPoint touchLocation = [t locationInView:self.view]; 
    NSLog(@"%@", NSStringFromCGPoint(touchLocation)); 
} 


- (IBAction)buttongDragged:(id)button withEvent:(UIEvent*)event { 
    NSSet *touches = [event touchesForView:button]; 
    [self touchesMoved:touches withEvent:event]; 
} 

注意,因爲touchesMoved:withEvent:UIResponder的方法和控制器的視圖UIResponder這種方法也將被要求對這一觀點的觸摸事件。

+0

因爲我希望用戶能夠在別處拖動按鈕。我在上面編輯了更多的代碼。 – Andrew 2011-03-10 00:17:23

+0

我明白了。我不知道這是否是實現這種行爲的最佳方式,但是如果您絕對需要這樣做,您可以從事件觸及 - 'NSSet * touches = [event touchesForView:sender]' – hoha 2011-03-10 00:23:44

+0

我會在哪裏放置該代碼? – Andrew 2011-03-10 00:40:16