0

我有一个 UIButton 将 draginside 事件发送到:

-(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

1 回答 1

4

当您添加目标以进行控制时,您可以传递 3 种类型的选择器进行操作 -

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

名称并不重要,重要的是参数的数量。如果控件向它的目标发送带有 2 个参数的消息,那么第一个参数将是控件本身(UIButton在您的情况下为实例),第二个参数是UIEvent. 但是您希望 instance of作为第一个参数并向其NSSet发送不理解的消息。这就是崩溃的原因。anyObjectUIButton

为什么您首先尝试将事件从 UI 控件发送到触摸处理方法touchesMoved:withEvent:?它可能会做一些与你的意思不同的事情。

更新:

- (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:is aUIResponder的方法和控制器的视图 UIResponder此方法也将在此视图的触摸事件上调用。

于 2011-03-10T00:13:37.467 回答