【问题标题】:UIButton crashes on uitouch eventUIButton 在 uitouch 事件上崩溃
【发布时间】:2011-03-09 23:32:23
【问题描述】:

我有一个 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];
}

【问题讨论】:

    标签: iphone objective-c uibutton uitouch


    【解决方案1】:

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

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

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

    您为什么首先尝试将事件从 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:UIResponder 的方法和控制器的视图 UIResponder 此方法也将在此视图的触摸事件上调用。

    【讨论】:

    • 因为我希望用户能够将按钮拖到其他地方。我在上面编辑了更多代码。
    • 我明白了。我不知道这是否是实现这种行为的最佳方式,但如果你绝对需要这个,你可以从事件中获得联系 - NSSet *touches = [event touchesForView:sender]
    • 嗯,我还是不明白。您可以在上面的答案中编辑一个示例吗?
    • 没关系,我解决了。我会将您的答案编辑到我的问题中,以供人们将来参考。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多