How to properly use swipeWithEvent to navigate a webView, Obj-C

后端 未结 3 413
旧巷少年郎
旧巷少年郎 2020-12-24 04:09

I want to implement the ability to navigate back and fourth in my webView by using the Event swipeWithEvent. However, I have no idea how I am suppose to use this.

I

3条回答
  •  鱼传尺愫
    2020-12-24 04:35

    I used touchesBeganWithEvent: and touchesEndedWithEvent: methods in NSViewController class. The following codes are just a crude example. For some reason, swipeWithEvent: just never gets fired. So I gave up on this (swipeWithEvent). The following codes were tested in High Sierra with Xcode 10 (inside the implementation section of a view controller):

    - (void)viewDidAppear {
           [super viewDidAppear];

    [self.view setAcceptsTouchEvents:YES]; } float beginX, endX; - (void)touchesBeganWithEvent:(NSEvent *)event { if(event.type == NSEventTypeGesture){ NSSet *touches = [event touchesMatchingPhase:NSTouchPhaseAny inView:self.view]; if(touches.count == 2){ for (NSTouch *touch in touches) { beginX = touch.normalizedPosition.x; } // since there are two touches, beginX will always end up with the data from the second touch } } } - (void)touchesEndedWithEvent:(NSEvent *)event { if(event.type == NSEventTypeGesture){ NSSet *touches = [event touchesMatchingPhase:NSTouchPhaseAny inView:self.view]; if(touches.count == 2){ for (NSTouch *touch in touches) { endX = touch.normalizedPosition.x; } // since there are two touches, endX will always end up with the data from the second touch if (endX > beginX) { NSLog(@"swipe right!"); } else if (endX < beginX) { NSLog(@"swipe left!"); } else { NSLog(@"no swipe!"); } } } }

    The [self.view setAcceptsTouchEvents:YES]; statement is very important. I put it in the viewDidAppear method so to start accepting touch info after all the views appear. If you are using this in a subclass, just changing self.view to self will do (also need the "setAcceptsTouchEvents" somewhere in the initialisation or drawRect). This is just an example of detecting swipe left and right. For swipe up and down, you need to use the touch.normalizedPosition.y data.

    If you are using it inside a NSWindowController subclass, you need this line self.window.contentView.acceptsTouchEvents=YES; in your windowDidLoad. You may also need to set your OSX target to 10.10 for all these to work as setAcceptsTouchEvents has already deprecated for higher versions.

提交回复
热议问题