简体   繁体   中英

How to pass a panGesture in a button to a tableView? (Swift 4)

I have a segmentedControl that sits inside the header of a tableView. When it picks up a panGesture I want it to scroll the enclosing tableView as if I were swiping up or down elsewhere on the table.

I added a panGesture:

let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePanGesture(_:)))
segmentedControl.addGestureRecognizer(panGestureRecognizer)

The only thing that comes close to doing what I want is the following. But it doesn't behave the same as if I swipe the tableView normally. Once the panGesture is done the tableView doesn't move back to the original position. There is no bounce back.

@objc func handlePanGesture(_ panGesture: UIPanGestureRecognizer) {
    let translation = panGesture.translation(in: segmentedVotingControl)
    panGesture.setTranslation(CGPoint.zero, in: segmentedVotingControl)
        tableView.contentOffset = CGPoint(x: tableView.contentOffset.x, y: tableView.contentOffset.y - translation.y)
}

I also tried something like this but it just locks up the table. It does not scroll:

segmentedVotingControl.addGestureRecognizer(tableView.panGestureRecognizer)

The regular "tap" gesture on the segmentedControl is handled like this:

@objc func segmentedVotingControlAction(sender: UISegmentedControl) {
     // actions to perform on tap
}
segmentedControl.addTarget(self, action: #selector(segmentedVotingControlAction(sender:)), for: .valueChanged)

Any ideas? Am I on the right track? It seems I should be able to somehow passthrough the panGesture to the tableView.

You should be able to get the value of the panGesture (the amount moved) and then pass it to a function which scrolls the tableView like this:

func scrollTableView(amount: CGFloat) {
    let point: CGPoint = CGPoint(x: 0.0, y: amount)
    tableView.setContentOffset(point, animated: true)
}

You'll need to test if animated should be false.

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