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

时间:2018-03-14 14:18:30

标签: ios swift rotation

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

    @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 / 2 {
        return .left
    }

    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)
}

1 个答案:

答案 0 :(得分:2)

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

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

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