Swift: 使用约束平移 UIImage
Swift: Pan UIImage using constraints
我的 viewController
中有一个 UIImage
,我正在使用 UIPanGesture
。我目前正在使用以下代码根据 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)
}
我正在为这个应用程序使用 auto layout
,并被告知应该将 UIImage
移动到 autoLayoutConstraints
。我更改为以下代码来移动 image
,但是,图像现在在整个屏幕上跳跃。
let translation = sender.translationInView(self.view)
image1ConstraintX.constant = image1ConstraintX.constant + translation.x
image1ConstraintY.constant = image1ConstraintY.constant + translation.y
有没有更好的方法使用 constraints
移动 image
?是否可以使用第一种方法,然后根据最终位置更新constraints
?如果正确完成,第二种移动 image
的方法会怎样?
一般来说,如果视图具有活动的自动布局约束,则不应直接设置其 frame
。这是因为下次布局引擎传递相关视图时,您的更改将被覆盖,而您无法控制何时发生。
您更新相关约束 constant
的解决方案是正确的。如果您发现自己经常这样做,您可能想要编写一个方法,它接受一个 CGPoint
和一个视图,并更新相关的约束。
Can the first method be used and then the constraints updated afterwards based on the final position?
是的,但您可能不想这样做。为此,您将删除或禁用约束,在用户平移时修改 frame
,并且在用户完成平移后,在每个约束上设置 constant
,然后重新启用布局约束。这将比必要的更复杂。
我的 viewController
中有一个 UIImage
,我正在使用 UIPanGesture
。我目前正在使用以下代码根据 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)
}
我正在为这个应用程序使用 auto layout
,并被告知应该将 UIImage
移动到 autoLayoutConstraints
。我更改为以下代码来移动 image
,但是,图像现在在整个屏幕上跳跃。
let translation = sender.translationInView(self.view)
image1ConstraintX.constant = image1ConstraintX.constant + translation.x
image1ConstraintY.constant = image1ConstraintY.constant + translation.y
有没有更好的方法使用 constraints
移动 image
?是否可以使用第一种方法,然后根据最终位置更新constraints
?如果正确完成,第二种移动 image
的方法会怎样?
一般来说,如果视图具有活动的自动布局约束,则不应直接设置其 frame
。这是因为下次布局引擎传递相关视图时,您的更改将被覆盖,而您无法控制何时发生。
您更新相关约束 constant
的解决方案是正确的。如果您发现自己经常这样做,您可能想要编写一个方法,它接受一个 CGPoint
和一个视图,并更新相关的约束。
Can the first method be used and then the constraints updated afterwards based on the final position?
是的,但您可能不想这样做。为此,您将删除或禁用约束,在用户平移时修改 frame
,并且在用户完成平移后,在每个约束上设置 constant
,然后重新启用布局约束。这将比必要的更复杂。