0

The problem in short, related to working with pan gesture inside a scrollView.

  1. I have a canvas(which is an UIView itself but bigger in size) where i am drawing some UIView objects with pan gesture enabled over each of them(Each little UIView Objects I am talking about, are making using another UIView class).

  2. Now the canvas can be bigger in height and width...which can be changed as per the user input.

  3. So to achieve that I have placed the canvas inside a UIScrollView. Now the canvas is increasing or decreasing smoothly.

  4. Those tiny UIView objects on the canvas can be rotated also.

Now the problem.

  1. If I am not changing the canvas size(static) i.e. if its not inside the scrollview then each UIView objects inside the canvas are moving superbly and everything is working just fine with the following code.

  2. If the canvas is inside the UIScrollView then the canvas can be scrollable right? Now inside the scrollview if I am panning the UIView objects on the canvas then those little UIView objects are not following the touch of the finger rather than its moving on another point when touch is moving on the canvas.

N.B. - Somehow I figured out that I need to disable the scrolling of the scrollview when any of the subviews are getting touch. For that thing I have implemented NSNotificationCenter to pass the signal to the parent viewController.

Here is the code.

This functions are defined inside the parent viewController class

func canvusScrollDisable(){
    print("Scrolling Off")
    self.scrollViewForCanvus.scrollEnabled = false
}
func canvusScrollEnable(){
    print("Scrolling On")
    self.scrollViewForCanvus.scrollEnabled = true
}

override func viewDidLoad() {
    super.viewDidLoad()
    notificationUpdate.addObserver(self, selector: "canvusScrollEnable", name: "EnableScroll", object: nil)
    notificationUpdate.addObserver(self, selector: "canvusScrollDisable", name: "DisableScroll", object: nil)
 }

This is the Subview class of the canvas

import UIKit

class ViewClassForUIView: UIView {
let notification: NSNotificationCenter = NSNotificationCenter.defaultCenter()

var lastLocation: CGPoint = CGPointMake(0, 0)
var lastOrigin = CGPoint()
var myFrame = CGRect()
var location = CGPoint(x: 0, y: 0)
var degreeOfThisView = CGFloat()
override init(frame: CGRect){
    super.init(frame: frame)

    let panRecognizer = UIPanGestureRecognizer(target: self, action: "detectPan:")
    self.backgroundColor = addTableUpperViewBtnColor
    self.multipleTouchEnabled = false
    self.exclusiveTouch = true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func detectPan(recognizer: UIPanGestureRecognizer){
    let translation = recognizer.translationInView(self.superview!)
    self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
    switch(recognizer.state){
    case .Began:
    break
    case .Changed:
    break
    case .Ended:
        notification.postNotificationName("EnableScroll", object: nil)
    default: break
    }
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    notification.postNotificationName("DisableScroll", object: nil) 
    self.superview?.bringSubviewToFront(self)
    lastLocation = self.center
    lastOrigin = self.frame.origin
    let radians:Double = atan2( Double(self.transform.b), Double(self.transform.a))
    self.degreeOfThisView = CGFloat(radians) * (CGFloat(180) / CGFloat(M_PI) )
    if self.degreeOfThisView != 0.0{
        self.transform = CGAffineTransformIdentity
        self.lastOrigin = self.frame.origin
        self.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))            
    }
    myFrame = self.frame
  }

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    notification.postNotificationName("EnableScroll", object: nil)
  }
   }

Now the scrollView is disabling its scroll perfectly whenever one of the UIView object is receiving touch over the canvas which is inside the scrollview but sometimes those UIView objects are not properly following the touch location over the canvas/screen.

I am using Swift 2.1 with Xcode 7 but anyone can tell me the missing things of mine or the solution using Objective-c/Swift?

halfer
  • 19,824
  • 17
  • 99
  • 186
onCompletion
  • 6,500
  • 4
  • 28
  • 37

1 Answers1

1

Where do you set the lastLocation? I think it would be better for you to use locationInView and compute the translation by yourself. Then save the lastLocation on every event that triggers the method.

Also you might want to handle the Cancel state as well to turn the scrolling back on.

All of this does seem a bit messy though. The notifications are maybe not the best idea in your case nor is putting the gesture recognizers on the subviews. I think you should have a view which handles all those small views; it should also have a gesture recognizer that can simultaneously interact with other recognizers. When the gesture is recognized it should check if any of the subviews are hit and decide if any of them should be moved. If it should be moved then use the delegate to report that the scrolling must be disabled. If not then cancel the recognizer (disable+enable does that). Also in most cases where you put something movable on the scrollview you usually want a long press gesture recognizer and not a pan gesture recognizer. Simply use that one and set some very small minimum press duration. Note that this gesture works exactly the same as the pan gesture but can have a small delay to be detected. It is very useful in these kind of situations.

Update (The architecture):

The hierarchy should be:

View controller -> Scrollview -> Canvas view -> Small views

The canvas view should contain the gesture recognizer that controls the small views. When the gesture begins you should check if any of the views are hit by its location by simply iterating through the subviews and check if their frame contains a point. If so it should start moving the hit small view and it should notify its delegate that it has began moving it. If not it should cancel the gesture recognizer.

As the canvas view has a custom delegate it is the view controller that should implement its protocol and assign itself to the canvas view as a delegate. When the canvas view reports that the view dragging has begin it should disable the scrollview scrolling. When the canvas view reports it has stopped moving the views it should reenable the scrolling of the scroll view.

  • Create this type of view hierarchy
  • Create a custom protocol of the canvas view which includes "did begin dragging" and "did end dragging"
  • When the view controller becomes active assign self as a delegate to the canvas view. Implement the 2 methods to enable or disable the scrolling of the scroll view.
  • The canvas view should add a gesture recognizer to itself and should contain an array of all the small movable subviews. The recognizer should be able to interact with other recognizers simultaneously which is done through its delegate.
  • The Canvas gesture recognizer target should on begin check if any of the small views are hit and save it as a property, it should also save the current position of the gesture. When the gesture changes it should move the grabbed view depending on the last and current gesture location and re-save the current location to the property. When the gesture ends it should clear the currently dragged view. On begin and end it should call the delegate to notify the change of the state.
  • Disable or enable the scrolling in the view controller depending on the canvas view reporting to delegate.

I think this should be all.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • Thanks for the idea..Yeah!! those subviews are inside a superview type which is called as canvas. The canvas is inside the scrollview...If possible, can you please give some explanation or some sudo type code or may be a little tute... – onCompletion Feb 26 '16 at 11:13
  • Cooll...!!!!!! Just Cool mate..no words for your effort...By the way I have solved the general issue about the view is not following touch on screen by using you idea as "Where do you set the lastLocation? I think it would be better for you to use locationInView and compute the translation by yourself. Then save the lastLocation on every event that triggers the method.".....Just giving the answer +1 because of cool and clear idea...:) – onCompletion Feb 26 '16 at 11:45