3

我有一个受自动布局约束的 UIView。它居中并且对宽度和高度有约束。当它出现时,我正在对其应用旋转变换。

旋转视图

当我点击那个动画按钮时,我希望它动画到屏幕上更高的点,同时旋转回“直立”位置(即不应用旋转)。所以,我设置了一个新的翻译变换:

let translation = CGAffineTransform(translationX: 1, y: -100)
UIView.animate(withDuration: 0.5, animations: {
   self.blueView.transform = translation
})

我期望看到的是视图在向上平移时旋转回直立位置。

相反,我得到的是视图“跳”到右侧的一个点,然后在旋转时向上动画。

我该如何解决这个问题,使其在动画之前不会“跳跃”?

在此处输入图像描述

4

1 回答 1

1

您正在看到跳跃,因为在blueView为平移变换设置动画时已经设置了旋转变换。这会导致意想不到的结果。

为了使其工作,您在动画之前结合旋转和平移变换然后重置动画变换:

要将蓝色视图向上平移 100pt并将其旋转回正常状态,请执行以下操作:

  1. 添加一个变换,将其向下blueView平移100pt并将其旋转 45°
  2. 将 centerYAnchor 常量设置为-100以使 blueView 在动画之前处于正确位置。
  3. 动画blueView.transform = .identity删除变换动画

这是一个工作示例:

class ViewController: UIViewController {

    let blueView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        blueView.backgroundColor = .blue
        view.addSubview(blueView)

        blueView.transform = CGAffineTransform(translationX: 0, y: 100).rotated(by: -CGFloat.pi / 4)

        let button = UIButton(type: .custom)
        button.setTitle("Animate", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(didPress), for: .touchUpInside)
        view.addSubview(button)

        blueView.translatesAutoresizingMaskIntoConstraints = false
        button.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            blueView.widthAnchor.constraint(equalToConstant: 20),
            blueView.heightAnchor.constraint(equalToConstant: 20),
            blueView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            blueView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -100),

            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40)
            ])
    }

    @objc func didPress(sender: UIButton) {
        UIView.animate(withDuration: 0.5, animations: {
            self.blueView.transform = .identity
        })
    }
}
于 2017-11-21T20:42:04.307 回答