Reputation: 837
I need to drag my to view about 2/3 part of a screen width to the right to expose a sub-view (containing a tableview) and then drag it back after inter-acting with the tableview.
The UIPanGestureRecognizer
seems to be what I need but after reading Apple's documentation I can't figure out the code needed in swift.
So to clarify - I have a view for capturing user data and I have a tableview
that contains telephone labels and numbers - I want to be able to drag the user view, expose the table and then drag the user view back.
@IBAction func panPiece(_ gestureRecognizer : UIPanGestureRecognizer) {
// Move the anchor point of the view's layer to the touch point
// so that moving the view becomes simpler.
let piece = gestureRecognizer.view
self.adjustAnchorPoint(gestureRecognizer: gestureRecognizer)
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
// Get the distance moved since the last call to this method.
let translation = gestureRecognizer.translation(in: piece?.superview)
// Set the translation point to zero so that the translation distance
// is only the change since the last call to this method.
piece?.center = CGPoint(x: ((piece?.center.x)! + translation.x),
y: ((piece?.center.y)! + translation.y))
gestureRecognizer.setTranslation(CGPoint.zero, in: piece?.superview)
}
}
func adjustAnchorPoint(gestureRecognizer : UIGestureRecognizer) {
if gestureRecognizer.state == .began {
let view = gestureRecognizer.view
let locationInView = gestureRecognizer.location(in: view)
let locationInSuperview = gestureRecognizer.location(in: view?.superview)
// Move the anchor point to the touch point and change the position of the view
view?.layer.anchorPoint = CGPoint(x: (locationInView.x / (view?.bounds.size.width)!),
y: (locationInView.y / (view?.bounds.size.height)!))
view?.center = locationInSuperview
}
}
Upvotes: 1
Views: 988
Reputation: 945
For attaching a gesture with a view
let panGesture = UIPanGestureRecognizer(target: self, action:#selector(handlePanGesture))
@objc private func handlePanGesture(sender:UIPanGestureRecognizer)
{
var translation = sender.translation(in: self)
sender.view?.superview?.bringSubview(toFront: sender.view!)
sender.view?.center = CGPoint(x: (sender.view?.center.x)! + translation.x , y : (sender.view?.center.y)! + translation.y)
sender.setTranslation(CGPoint.zero, in: self)
}
Upvotes: 1