Created
March 8, 2018 01:45
-
-
Save bricklife/cc2fd7a2075edec3ff6117985a7bbf14 to your computer and use it in GitHub Desktop.
UIPanGestureRecognizer on UIScrollView
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
// | |
// ViewController.swift | |
// PanOnScroll | |
// | |
// Created by Shinichiro Oba on 2018/03/08. | |
// Copyright © 2018 bricklife.com. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var topMargin: NSLayoutConstraint! | |
weak var scrollView: UIScrollView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:))) | |
pan.delegate = self | |
scrollView.addGestureRecognizer(pan) | |
move(0) | |
} | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
let nav = segue.destination as! UINavigationController | |
let table = nav.childViewControllers.first as! UITableViewController | |
scrollView = table.tableView | |
} | |
func move(_ y: CGFloat) { | |
topMargin.constant = 100 + y | |
} | |
var start: CGFloat = 0 | |
@objc func pan(_ pan: UIPanGestureRecognizer) { | |
let position = pan.location(in: view) | |
switch pan.state { | |
case .began: | |
start = position.y + scrollView.contentOffset.y | |
case .changed: | |
let diff = position.y - start | |
if diff > 0 { | |
move(diff) | |
scrollView.contentOffset = .zero | |
scrollView.showsVerticalScrollIndicator = false | |
} else { | |
move(0) | |
scrollView.showsVerticalScrollIndicator = true | |
} | |
default: | |
move(0) | |
scrollView.showsVerticalScrollIndicator = true | |
UIView.animate(withDuration: 0.2) { | |
self.view.layoutIfNeeded() | |
} | |
} | |
} | |
} | |
extension ViewController: UIGestureRecognizerDelegate { | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment