视图通过平移手势在旋转时奇怪地移动

我在一个按钮上有一个平移手势,可以在平移方向上移动按钮。 当翻译“足够远”时,按钮会旋转。 在此旋转时,按钮可见到达其初始位置或关闭,然后返回到应该的位置。 无法弄清楚发生了什么。 这是我的代码:

@IBAction func didPanButton(_ sender: UIPanGestureRecognizer) { print("Did pan button", sender.translation(in: sender.view).x) answerButton.center.x = view.center.x + sender.translation(in: sender.view).x switch buttonPosition { case .left: print("Rotate button left") UIView.animate(withDuration: 0.5, animations: { self.rotateButtonLeft() }) case .right: print("Rotate button right") UIView.animate(withDuration: 0.5, animations: { self.rotateButtonRight() }) case .middle: print("Remove button rotation") UIView.animate(withDuration: 0.5, animations: { self.removeButtonRotation() }) } } var buttonPosition : ButtonPosition { let leftWidth = (view.frame.size.width - answerButton.frame.size.width) / 2 if answerButton.frame.origin.x  leftWidth * 3 / 2 { return .right } return .middle } func rotateButtonLeft() { let degrees : CGFloat = -10; //the value in degrees answerButton.transform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi/180); let image = UIImage(named: "item_no") answerButton.setImage(image, for: UIControlState.normal) } func rotateButtonRight() { let degrees : CGFloat = 10; //the value in degrees answerButton.transform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi/180); let image = UIImage(named: "item_yes") answerButton.setImage(image, for: UIControlState.normal) } func removeButtonRotation() { let degrees : CGFloat = 0; //the value in degrees answerButton.transform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi/180); let image = UIImage(named: "item_neutral") answerButton.setImage(image, for: UIControlState.normal) } 

您的按钮具有设置其位置的约束。 当自动布局运行时,它会根据这些约束重置按钮的center 。 设置按钮的图像会触发自动布局。

您有三种方法可以解决此问题:

  1. 通过更新约束OR来更改按钮的位置
  2. 通过设置transform而不是通过更改其center OR来更改按钮的位置
  3. 不要使用约束来定位按钮。