[英]Swift: Pan UIImage using constraints
I have an UIImage
in my viewController
that I am using the UIPanGesture
on. 我的
viewController
中有一个UIImage
,正在使用UIPanGesture
。 I am currently using the following code to move it around based on the RayWenderlich tutorial. 我目前正在根据RayWenderlich教程使用以下代码来移动它。
@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. 我正在为此应用程序使用
auto layout
,并被告知应改为使用autoLayoutConstraints
移动UIImage
。 I changed to the following code to move the image
, however, the image is now jumping all over the screen. 我更改为以下代码来移动
image
,但是图像现在在整个屏幕上跳跃。
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
? 有没有使用
constraints
移动image
的更好方法? Can the first method be used and then the constraints
updated afterwards based on the final position? 可以使用第一种方法,然后根据最终位置更新
constraints
吗? And how would the second method of moving the image
look if done correctly? 如果正确完成,第二种移动
image
方法会如何?
Generally speaking, if a view has active auto layout constraints you should not set its frame
directly. 一般来说,如果视图具有有效的自动布局约束,则不应直接设置其
frame
。 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. 您更新相关约束
constant
的解决方案是正确的。 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. 如果您发现自己做了很多事情,则可能需要编写一个使用
CGPoint
和视图并更新相关约束的方法。
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. 为此,您将删除或禁用约束,在用户平移时修改
frame
,并在用户完成平移后,在每个约束上设置constant
,然后重新启用布局约束。 This would be more complex than is necessary. 这将比必需的更为复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.