Stopping a UIView container with UIPanGesture?

I managed to stop my UIView going beyond the container using pan gestures, but I try my best to stop it around the edges. Currently, it goes straight to the last edge of the pixel, and not to the edge of the moved view.

I tried to change the value of the frame, which, in my opinion, is a way out, but cannot lead to the correct results. Not sure how close I have or have an easier way?

How would I stop it at the edges of the moved view instead of the last pixel? enter image description here

//Container is self.sliderContainer //Green Block is sender.view which has a UIGesture applied var location = sender.locationInView(self.view) var newFrame = CGRectMake(0, 0, self.sliderContainer.frame.width, self.sliderContainer.frame.height) let obstacleViewFrame = self.view.convertRect(self.sliderContainer.frame, fromView: self.sliderContainer.superview) // Check if the touch is inside the obstacle view if CGRectContainsPoint(obstacleViewFrame, location) { sender.view!.center.x = sender.view!.center.x + translation.x sender.setTranslation(CGPointZero, inView: self.view) } 
+4
source share
2 answers

I would recommend doing this in the easiest way, without restricting the gesture, just making sure that rect doesn't go beyond:

 let movingView = sender.view! let minCenterX = movingView.frame.size.width / 2 let maxCenterX = self.sliderContainer.frame.width - movingView.frame.size.width / 2 let newCenterX = movingView.center.x + translation.x movingView.center.x = min(maxCenterX, max(minCenterX, newCenterX)) 
+2
source

It looks like you are basing the movement of the sender view on the slide based on the touch coordinates, not the sender.view frame.

 let senderViewFrame = self.view.convertRect(sender.view!.frame, fromView: sender.view!.superview) let insetSenderViewFrame = CGRectInset(senderViewFrame, 0.0, 10.0 /*or whatever needed*/) let obstacleViewFrame = self.view.convertRect(self.sliderContainer.frame, fromView: self.sliderContainer.superview) // Check if the sender view is inside the obstacle view if CGRectContainsRect(obstacleViewFrame, insetSenderViewFrame) { sender.view!.center.x = sender.view!.center.x + translation.x sender.setTranslation(CGPointZero, inView: self.view) } 
+1
source

All Articles