您正在看到跳跃,因为在blueView
为平移变换设置动画时已经设置了旋转变换。这会导致意想不到的结果。
为了使其工作,您在动画之前结合旋转和平移变换,然后重置动画变换:
要将蓝色视图向上平移 100pt并将其旋转回正常状态,请执行以下操作:
- 添加一个变换,将其向下
blueView
平移100pt并将其旋转 45°
- 将 centerYAnchor 常量设置为-100以使 blueView 在动画之前处于正确位置。
- 动画
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
})
}
}