cs193p – Project #3 Assignment #3 Task #11

By ProtoplasmaKid (Own work) [CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

Please note, this blog entry is from a previous course. You might want to check out the current one.

Your graphing view must support the following three gestures:
a. Pinching (zooms the entire graph, including the axes, in or out on the graph)
b. Panning (moves the entire graph, including the axes, to follow the touch around)
c. Double-tapping (moves the origin of the graph to the point of the double tap)


Let’s start by implement the handlers in the graph view class. Pinching zooms the view, thus we have to change the scale of the view:

    func zoom(gesture: UIPinchGestureRecognizer) {
        if gesture.state == .Changed {
            scale *= gesture.scale
            gesture.scale = 1.0
        }
    }


Panning moves the view, thus we change the origin of the view:

    func move(gesture: UIPanGestureRecognizer) {
        switch gesture.state {
        case .Ended: fallthrough
        case .Changed:
            let translation = gesture.translationInView(self)
            origin.x += translation.x
            origin.y += translation.y
            gesture.setTranslation(CGPointZero, inView: self)
        default: break
        }
    }

Double tapping center the view, thus we set the center to the tapping position:

    
    func center(gesture: UITapGestureRecognizer) {
        if gesture.state == .Ended {
            origin = gesture.locationInView(self)
        }
    }

The switching on of the gestures happens in the graph view controller, when the graph view just has been set. For pinching and panning just add the recognizer to the view. For double tapping, and additional adjustment of the number of required taps is necessary:

    @IBOutlet weak var graphView: GraphView! {
        didSet {
            graphView.dataSource = self
            graphView.addGestureRecognizer(UIPinchGestureRecognizer(target: graphView, action: "zoom:"))
            graphView.addGestureRecognizer(UIPanGestureRecognizer(target: graphView, action: "move:"))
            var tap = UITapGestureRecognizer(target: graphView, action: "center:")
            tap.numberOfTapsRequired = 2
            graphView.addGestureRecognizer(tap)
        }
    }

The complete code for the task #11 is available on GitHub.

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *