Last active
August 12, 2017 08:28
-
-
Save yamazaki-sensei/3bc0663531900fc2bf9299a24fd6ec69 to your computer and use it in GitHub Desktop.
iOSのMKMapViewで、GoogleMap的なダブルタップ → 上下スライド でのズームイン・アウトとダブルタップでのズームを共存させる ref: http://qiita.com/almichest/items/fb792a5a157d4b5956f1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import MapKit | |
| class ViewController: UIViewController { | |
| /* ドラッグの位置記憶用の変数 */ | |
| var dragPoint: CGPoint? | |
| var mapView: MKMapView! | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| mapView = MKMapView(frame: view.bounds) | |
| view.addSubview(mapView) | |
| let doubleLongPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.doubleLongPress(_:))) | |
| /* ダブルタップ後、即座にLongPress状態に移るように */ | |
| doubleLongPress.minimumPressDuration = 0 | |
| doubleLongPress.numberOfTapsRequired = 1 | |
| mapView.addGestureRecognizer(doubleLongPress) | |
| doubleLongPress.delegate = self | |
| /* MKMapViewの機能が実装してあるSubViewを引っ張ってきて、設定してあるDoubleTapGestureRecognizerにdelegateを設定する */ | |
| mapView.subviews[0].gestureRecognizers?.forEach({ (element) in | |
| if let recognizer = (element as? UITapGestureRecognizer) where recognizer.numberOfTapsRequired == 2 { | |
| element.delegate = self | |
| } | |
| }) | |
| } | |
| } | |
| extension ViewController: UIGestureRecognizerDelegate { | |
| /* このzoomメソッドの実装は適当 */ | |
| func zoom(magnification: Double) { | |
| var region = mapView.region | |
| let span = region.span | |
| region.span = MKCoordinateSpan(latitudeDelta: span.latitudeDelta * magnification, longitudeDelta: span.longitudeDelta * magnification) | |
| mapView.setRegion(region, animated: false) | |
| } | |
| /* ダブルタップ → 上下動 で、ズームイン / アウト する (GoogleMap的な挙動) */ | |
| func doubleLongPress(recognizer: UILongPressGestureRecognizer) { | |
| let state = recognizer.state | |
| let location = recognizer.locationInView(recognizer.view) | |
| switch state { | |
| case .Began: | |
| dragPoint = location | |
| case .Changed: | |
| /* 上に動いたか下に動いたか判断 */ | |
| let diffY = Double(location.y - dragPoint!.y) | |
| let magnification = 1 - diffY * 0.01 | |
| self.zoom(magnification) | |
| dragPoint = location | |
| default: | |
| break | |
| } | |
| } | |
| /* MKMapViewに元から設定されているDoubleTapと、自分で設定したLongPressを同時に機能させる */ | |
| func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { | |
| return true | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment