I have an UIImage
in my viewController
that I am using the UIPanGesture
on. I am currently using the following code to move it around based on the RayWenderlich tutorial.
@IBAction func panImage(sender: UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
exitButton1.center = CGPoint(x:exitButton1.center.x + translation.x, y:exitButton1.center.y + translation.y)
}
sender.setTranslation(CGPointZero, inView: self.view)
}
I am using auto layout
for this app and have been informed that moving the UIImage
with autoLayoutConstraints
should be done instead. I changed to the following code to move the image
, however, the image is now jumping all over the screen.
let translation = sender.translationInView(self.view)
image1ConstraintX.constant = image1ConstraintX.constant + translation.x
image1ConstraintY.constant = image1ConstraintY.constant + translation.y
Is there a better way of moving the image
using the constraints
? Can the first method be used and then the constraints
updated afterwards based on the final position? And how would the second method of moving the image
look if done correctly?
Generally speaking, if a view has active auto layout constraints you should not set its frame
directly. This is because your change will get overwritten the next time the layout engine makes a pass over the relevant views, and you cannot control when that will happen.
Your solution to update the constant
of the relevant constraints is the correct one. If you find yourself doing this a lot, you may want to write a method that takes a CGPoint
and a view, and updates the relevant constraints.
Can the first method be used and then the constraints updated afterwards based on the final position?
Yes, but you probably don't want to. To accomplish this, you would remove or disable the constraints, modify frame
as the user pans, and once the user is done panning, set the constant
on each constraint, and re-enable the layout constraints. This would be more complex than is necessary.
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.