I know there have been similar questions asked, but none of them have worked for me.
I have this code to enable swiping back in my project
class InteractivePopRecognizer: NSObject {
// MARK: - Properties
fileprivate weak var navigationController: UINavigationController?
// MARK: - Init
init(controller: UINavigationController) {
self.navigationController = controller
super.init()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
}
extension InteractivePopRecognizer: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return (navigationController?.viewControllers.count ?? 0) > 1
}
// This is necessary because without it, subviews of your top controller can cancel out your gesture recognizer on the edge.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
I have this VC stack
HomescreenVC -> Login/SignupVC -> UserProfileVC
I do not want them to be able to swipe back from the UserProfileVC.
A better approach is to clear them from the stack when you show UserProfileVC
let profile = self.storyboard?.instantiateViewController(withIdentifier: "profileID") as! UserProfileVC
self.navigationController?.viewControllers = [profile]
Edit: Do this inside profileVC
self.navigationController?.viewControllers = [self]
//
self.view.alpha = 0
UIView.animate(withDuration: 0.5) {
self.view.alpha = 1
}
I think you can remove gesture Recognizer from there too why you are not trying that.
Try something like this:-
view.gestureRecognizers?.removeAll()
Related
I am displaying a PDF file and would like to add a screen edge gesture to move pages around.
The following code works fine when entire the content of a PDF is displayed on the screen. However, when the PDF was zoomed, the screen edge gesture cannot even activate.
override func viewDidLoad(){
super.viewDidLoad()
//set up gesture to swipe from the edge
let leftScreenEdgeRecognizer = UIScreenEdgePanGestureRecognizer (
target: self, action: #selector(TextDocumentViewController.leftEdgePanGestureHandler(_ : )))
leftScreenEdgeRecognizer.edges = UIRectEdge.left
let rightScreenEdgeRecognizer = UIScreenEdgePanGestureRecognizer (
target: self, action: #selector(TextDocumentViewController.rightEdgePanGestureHandler(_ : )))
rightScreenEdgeRecognizer.edges = UIRectEdge.right
//register the gesture
pdfView.addGestureRecognizer(leftScreenEdgeRecognizer)
pdfView.addGestureRecognizer(rightScreenEdgeRecognizer)
}
//gesture functions here
#objc func leftEdgePanGestureHandler(_ sender: UIScreenEdgePanGestureRecognizer){
if(sender.state == UIGestureRecognizer.State.ended){
print ("Left Edge")
pdfView.goToPreviousPage(sender)
}
}
#objc func rightEdgePanGestureHandler(_ sender: UIScreenEdgePanGestureRecognizer){
if(sender.state == UIGestureRecognizer.State.ended){
print ("right Edge")
pdfView.goToNextPage(sender)
}
}
I tired to add a code like,
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
However, this is not working at all.
I was able to solve this problem thanks to the answer provided for my old question. I have totally forgotten about the post. After learning more about multiple gesture detections through try and error, I realized that I can do as follows to solve this posted question:
Enables the multiple gesture activation:
class ViewController: UIViewController, UIGestureRecognizerDelegate, UIDocumentPickerDelegate, PDFViewDelegate {
// ... other things
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer:
UIGestureRecognizer) -> Bool {
return true
}
}
Make sure to appropriately set delegate.
override func viewDidLoad(){
super.viewDidLoad()
//set gesture
leftScreenEdgeRecognizer.delegate = self
rightScreenEdgeRecognizer.delegate = self
}
I am trying to respond to UICollectionViewCell selection:
private func setupCellAction() {
collectionView?.rx.itemSelected
.asObservable()
.subscribe(onNext: { [weak self] indexPath in
print("itemSelected!")
let cell = self?.collectionView?.cellForItem(at: indexPath) as? CellTypeCollectionViewCell
self?.performSegue(withIdentifier: "showBarchartSegue", sender: cell)
}).disposed(by: disposeBag)
}
But somehow onNext method is never called. I tried putting setupCellAction() in viewDidLoad, viewWillAppear and viewDidAppear but it is not working. Any suggestions would be greatly appreciated.
Update
I tried the suggestion from the following thread: How to select CollectionView cell in RxSwift
and added .debug("RX: Model selected") before the subscribe method. I see the output in the console that it is subscribed once.
Update
I tried rewriting the setupCellAction() in the following way:
private func setupCellAction() {
collectionView?.rx.modelSelected(CellTypeCollectionViewCell.self)
.asObservable()
.debug("RX: Model selected")
.subscribe(onNext: { [weak self] cell in
print("itemSelected!")
self?.performSegue(withIdentifier: "showBarchartSegue", sender: cell)
}).disposed(by: disposeBag)
}
It is not working either. I see also that it is subscribed once in the console.
Update
UICollectionViewController was embedded in another container UIViewController, and in it I defined UITapGestureRecognizer. After commenting out the code for the UITapGestureRecognizer, the itemSelected() method started to work. Right now I need a way to let the tap event through if it happened on the UICollectionViewCell. Is there a way to do that?
The code for tapping in the container controller (viewDidLoad):
let tap = UITapGestureRecognizer(target: self, action:
#selector(self.handleTap(_:)))
tap.delegate = self
view.addGestureRecognizer(tap)
The handleTap():
#objc func handleTap(_ sender: UITapGestureRecognizer) {
tableView.isHidden = true
searchBar.resignFirstResponder()
}
You can let taps through with the UIGestureRecognizerDelegate protocol and implementing the method
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool.
Basically, you need to return false whenever you touch a UICollectionViewCell, if I understood the problem correctly.
You can do this by using the method func indexPathForItem(at point: CGPoint) -> IndexPath? from the UICollectionView. If the given CGPoint matches a cell's location, you will get its IndexPath.
Don't forget to translate the touch location to the collection view's frame - you can use UITouch's func location(in view: UIView?) -> CGPoint for this.
It would probably look somewhat like this:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let point = touch.location(in: collectionView)
return collectionView.indexPathForItem(at: point) == nil
}
I am using spriteKit. I don't kwon whether this is important. I've initialized two UIGestureRecognizer to my view in didMove(toView):
let longPress = UILongPressGestureRecognizer()
longPress.minimumPressDuration = CFTimeInterval(0.0)
longPress.addTarget(self, action: #selector(self.longPressGesture(longpressGest:)))
self.view?.addGestureRecognizer(longPress)
let swipeUp = UISwipeGestureRecognizer()
swipeUp.direction = UISwipeGestureRecognizerDirection.up
swipeUp.addTarget(self, action: #selector(self.swipeUpGesture(swipe:)))
self.view?.addGestureRecognizer(swipeUp)
My Problem is that only the first gestureRecognizer is called (longpressGest). When I delete the first GestureRecognizer, the swipeGestureRecognizer does work. How can I solve this?
You need to make your Game Scene view the delegate of your gesture recognizer. You will also need implement its method shouldRecognizeSimultaneouslyWith as mentioned by xmasRights:
So in your Game scene declaration just add UIGestureRecognizerDelegate:
class GameScene: SKScene, SKPhysicsContactDelegate, UIGestureRecognizerDelegate {
And in your didMove(to view: SKView) method make set its delegate:
let longPress = UILongPressGestureRecognizer()
longPress.delegate = self
longPress.minimumPressDuration = 0
longPress.addTarget(self, action: #selector(longPressGesture))
view.addGestureRecognizer(longPress)
let swipeUp = UISwipeGestureRecognizer()
swipeUp.delegate = self
swipeUp.direction = .up
swipeUp.addTarget(self, action: #selector(swipeUpGesture))
view.addGestureRecognizer(swipeUp)
Also In Swift 4 you will need to add #objc to your methods
#objc func longPressGesture(_ longPress: UILongPressGestureRecognizer) {
print("longPressGesture")
}
#objc func swipeUpGesture(_ swipeUp: UISwipeGestureRecognizer) {
print("swipeUpGesture")
}
Don't forget also to add the method shouldRecognizeSimultaneouslyWith as already mentioned by xmasRights:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("shouldRecognizeSimultaneouslyWith")
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
return true
}
https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/coordinating_multiple_gesture_recognizers/allowing_the_simultaneous_recognition_of_multiple_gestures
You could also use the same gesture recognizer and differ between the two gesture inside of this function
In my UINavigationController I added custom back buttons with the side effect that it is not possible anymore to swipe left to right to pop the view controller and navigate back.
So I implemented interactivePopGestureRecognizer in my custom UINavigationController class:
class UINavigationControllerExtended: UINavigationController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if self.respondsToSelector(Selector("interactivePopGestureRecognizer")) {
self.interactivePopGestureRecognizer?.delegate = self
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return gestureRecognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer)
}
}
This works fine except when I am in my root view controller (RVC) which is a UICollectionViewController, i.e. the most bottom view controller in the navigation stack. When I do the swipe left to right gesture, nothing seems to happen, as expected. But when I then tap a UICollectionViewCell the destination view controller (DVC) does not get pushed over the RVC. Instead I only see the DVC's shadow on the right side of the screen.
The RVC is not responsive anymore, but as I swipe left to right again, the DVC interactively moves right to left into the screen. When I finish the gesture, the DVC moves completely into the screen just to quickly disappear left to right again. The RVC becomes responsive again.
So it seems the DVC gets pushed onto the navigation stack but not visibly into the screen.
Any suggestions where this strange behaviour originates?
Implement UINavigationControllerDelegate for your navigation controller and enable/disable the gesture recognizer there.
// Fix bug when pop gesture is enabled for the root controller
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.enabled = self.viewControllers.count > 1
}
Keeping the code independent from the pushed view controllers.
My current solution is to disable the interactivePopGestureRecognizer in the root view controller:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.interactivePopGestureRecognizer?.enabled = false
}
In the first child view controller I enable it again. But this seems to be more a workaround because I don't understand the actual problem why the navigation stack got messed up in the first place.
Here is my solution for this. Swift 4.2
Implement UIGestureRecognizerDelegate and UINavigationControllerDelegate protocols. In my case I did this in an UITabBarController that would be also my root view controller.
Then, on viewDidLoad, do:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
self.navigationController?.delegate = self
}
Then, add the delegate method for UINavigationControllerDelegate and check if it is the root view by counting the number of view on the navigation controller and disable it if it is or enable it if its not.
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
let enable = self.navigationController?.viewControllers.count ?? 0 > 1
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = enable
}
Lastly, add the UIGestureRecognizerDelegate method
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
This should fix the problem without the necessity of manually enabling/disabling the gesture recogniser in every view of your project.
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.isEnabled = self.viewControllers.count > 1
}
Updated #rivera solution for Swift 5
Solution from Guilherme Carvalho worked for me, but I had to assign delegate methods in viewWillAppear, in viewDidLoad was too late for my implementation.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.interactivePopGestureRecognizer?.delegate = self
navigationController?.delegate = self
}
Try this code
func navigationController(navigationController: UINavigationController, didShowViewController vc: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.enabled = self.vc.count > 1
}
i"m trying to implement a long press gesture recognizer on a WKWebView as follows:
var webView: WKWebView?
let longPressRecognizer = UILongPressGestureRecognizer()
override func loadView() {
super.loadView()
var webViewConfig: WKWebViewConfiguration = WKWebViewConfiguration()
webViewConfig.allowsInlineMediaPlayback = true
webViewConfig.mediaPlaybackRequiresUserAction = false
self.webView = WKWebView(frame: self.view.frame, configuration: webViewConfig)
self.view = self.webView!
//hook the long press event
longPressRecognizer.addTarget(self, action: "onLongPress:")
self.webView!.scrollView.addGestureRecognizer(longPressRecognizer)
}
func onLongPress(gestureRecognizer:UIGestureRecognizer){
NSLog("long press detected")
}
i don't get an error but i cant seem to make it trigger the onLongPress function.
You didn't set the delegate of the gesture recognizer.
//hook the long press event
longPressRecognizer.delegate = self
longPressRecognizer.addTarget(self, action: "onLongPress:")
self.webView!.scrollView.addGestureRecognizer(longPressRecognizer)
In case that it still doesn't work, this may probably due to WKWebView already has its own gesture recognizers. Then add the following method to your class:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
And in your event method check for the gesture began:
func onLongPress(gestureRecognizer:UIGestureRecognizer){
if gestureRecognizer.state == UIGestureRecognizerState.Began {
NSLog("long press detected")
}
}