【问题标题】:UIView with auto layout constraints "jumps" before transform animation具有自动布局约束的 UIView 在变换动画之前“跳跃”
【发布时间】:2018-05-02 23:02:48
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: ios autolayout ios-animations


    【解决方案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
            })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多