ios - Touch drag enter 如何工作?

标签 ios objective-c

谁能给我一个关于 Touch drag enter 从一个按钮拖动到另一个触发两个按钮事件的例子。 它是如何工作的?

比如我想从Do拖到Fa,触发Do、Re、Mi、Fa的事件。

iOS Simulator Screenshot

这是我的代码:

- (void) setupVC {
soundBankPlayer = [[SoundBankPlayer alloc] init];
[soundBankPlayer setSoundBank:@"Piano"];
arrMusicalNotes = [NSArray arrayWithObjects:@"60", @"62", @"64", @"65", @"67", @"69", @"71", @"72", nil];
}


#pragma mark - Setup Musical Note
- (IBAction)btnMusicalNoteclick:(id)sender {
    int numOfNote = [[arrMusicalNotes objectAtIndex:((UIButton*)sender).tag] intValue];
    NSLog(@"%i", numOfNote);
    [soundBankPlayer queueNote:numOfNote gain:1.0f];
    [soundBankPlayer playQueuedNotes];
}

- (IBAction)btnDragOut:(id)sender {
    NSLog(@"Out");
}

哦,我已经看到,当我在模拟器外按住鼠标不放时,会触发 btnDragOut 方法。当我从 Simulator 拖到按钮时,会触发此按钮的方法。 现在我希望当我拖出按钮时触发 btnDragOut 方法(手指仍在模拟器中)。有人知道吗?

最佳答案

您可以通过 Storyboard 或 viewDidLoad 方法中的代码将 UIPanGestureRecognizer 添加到您的 UIViewController 子类的 View 中:

UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
[self.view addGestureRecognizer:gestureRecognizer];

然后你可以在当前 UIButton 被拖动的 UIViewController 子类的实现文件中添加属性:

@interface YourViewController ()
@property (weak, nonatomic) UIButton *currentButton;
@end

现在在操作方法中,您可以检测 UIControlEventTouchDragEnterUIControlEventTouchDragExit 事件,如下所示:

- (void)handleDrag:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.view];
    UIView *draggedView = [self.view hitTest:point withEvent:nil];

    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        if ([draggedView isKindOfClass:[UIButton class]] && !self.currentButton) {
            self.currentButton = (UIButton *)draggedView;
            NSLog(@"Enter: %ld", (long)self.currentButton.tag);

            // send enter event to your button
            [self.currentButton sendActionsForControlEvents:UIControlEventTouchDragEnter];
        }

        if (self.currentButton && ![self.currentButton isEqual:draggedView]) {
            NSLog(@"Out: %ld", (long)self.currentButton.tag);

            // send exit event to your button
            [self.currentButton sendActionsForControlEvents:UIControlEventTouchDragExit];
            self.currentButton = nil;
        }
    } else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        self.currentButton = nil;
    }
}

关于ios - Touch drag enter 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31916979/

相关文章:

ios - 以编程方式设置约束时无法同时满足约束

ios - iOS Today 扩展中奇怪的 NSInternalInconsistencyException 和 PKService 崩溃

ios - 发送到 UIViewController(或协议(protocol))实例的无法识别的选择器?

ios - 如何调用initWithCoder?

ios - 我想存储 json 数据并在需要 ios 时使用它

ios - 获取当前位置而不是缓存 ios

ios - 对于 iPod Touch,我想让时钟在状态栏上出现两次。我该怎么做?

python - 使用 Kivy 访问 iPhone 照片库

ios - 如何使用 Storyboard纵横比自动设置按钮等于?

objective-c - 适用于 iOS 的 SBJson 静态库