简体   繁体   中英

Pairing my own UIPanGestureRecognizer with that of UIScrollView's

I have two views; a UIView placed on top of a UITableView . I need to know when the UIView has been panned, so I've placed a UIPanGestureRecognizer on it. However, this creates a UI which seems buggy because you expect the UITableView behind it to move as your finger does.

So it seems I need to somehow pair up this pan gesture with making the table view behind it move, at least, until this covering view disappears.

How do I pair up a pan gesture to move a UIScrollView ?

Note: If you're wondering about the cover view, it's actually a UIImageView which has a snapshot of the table view with a filter applied to it for UI reasons. When this view is panned, it disappears. So from the user's point of view, while they begin dragging the cover view, I want them to keep thinking they are dragging the table view as the cover disappears.

Assuming you have a view controller with a table view setup like the following:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate 
{

    @IBOutlet var tableView: UITableView!
    @IBOutlet var scrollView: UIScrollView!

You can add a couple of gesture recognizers:

    var gestureRecognizer1: UIPanGestureRecognizer = UIPanGestureRecognizer()
    var gestureRecognizer2: UIPanGestureRecognizer = UIPanGestureRecognizer()

Setup your delegates and add the gesture recognizers to the scroll views:

    override func viewDidLoad()
    {
        super.viewDidLoad()

        scrollView.contentSize = CGSizeMake( ) // <-- Set your content size.
        scrollView.delegate = self
        tableView.delegate = self
        gestureRecognizer1.delegate = self
        gestureRecognizer2.delegate = self
        tableView.addGestureRecognizer(gestureRecognizer1)
        scrollView.addGestureRecognizer(gestureRecognizer2)
    }

Implement a delegate method for UIGestureRecognizerDelegate to recognize simultaneous gestures:

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
    {
        return true
    }

Implement a delegate method for UIScrollViewDelegate :

    func scrollViewDidScroll(scrollView: UIScrollView) 
    {
        tableView.contentOffset = scrollView.contentOffset
    }
}

The movement of the tableView will be synchronized to the scroll view.

In the end I've decided to directly change the cell's images with a CIFilter rather than take a snapshot. This way is the way I should have done it anyway, it's much cleaner and uses no possibly-buggy “workarounds”.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM