【问题标题】:How to animate cross dissolve a view when added as a subview?添加为子视图时如何动画交叉溶解视图?
【发布时间】:2020-02-21 04:06:44
【问题描述】:

我在当前视图底部的UIViewController 中添加一个视图作为子视图。我可以使用 alpha 进行淡入淡出动画,但我想像弹出键盘一样显示它。

let popup: UIView = ..
popup.alpha = 0.0
self.view.addSubView(popup)
UIView.animate(withDuration: 0.3, animations: {
    popup.alpha = 1.0
}) { _ in
}

如何制作动画?

【问题讨论】:

  • 交叉溶解是一种淡入/淡出,就像您已经拥有的一样。您想将视图从屏幕底部移动到其最终位置?
  • 没有交叉溶解与淡入不同。您还需要淡出下面的视图。
  • @Daniel Storm:是的,类似于弹出键盘时。键盘从底部滑入并滑出。我正在寻找类似的动画。
  • @JoshHomann 在这个问题中没有提到另一种观点。
  • @DanielStorm 它清楚地表示视图正在添加到当前视图控制器上。

标签: ios swift


【解决方案1】:

您可以更新框架,但我喜欢使用变换制作动画,这样您仍然可以使用约束而不必弄乱它们。

let popup: UIView = ..
popup.transform = CGAffineTransform(translationX: 0, y: popup.bounds.height)
self.view.addSubView(popup)
UIView.animate(withDuration: 0.3, animations: {
    popup.transform = .identity
}) { _ in
}

假设视图位于屏幕底部,您将视图向下平移等于其高度的量,然后将变换动画化回它的标识,即原始位置。

【讨论】:

    【解决方案2】:

    要通过仅添加子视图来实现交叉淡入淡出,请尝试UIView.transition(with:duration:options:animations:completion:) 在动画块期间添加您的视图。

    一个快速的游乐场:

    //: A UIKit based Playground for presenting user interface
    
    import UIKit
    import PlaygroundSupport
    
    class MyViewController : UIViewController {
        override func loadView() {
            let view = UIView()
            view.backgroundColor = .white
    
            let label = UILabel()
            label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            label.text = "Hello World!"
            label.textColor = .black
    
            view.addSubview(label)
            self.view = view
        }
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            let orangeView = UIView(frame: CGRect(origin: CGPoint(x: view.bounds.midX, y: view.bounds.midY), size: CGSize(width: 100, height: 100)))
    
            orangeView.backgroundColor = .orange
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
                UIView.transition(with: self.view, duration: 0.6, options: .transitionCrossDissolve, animations: {
                    self.view.addSubview(orangeView)
                }) { _ in
    
                }
    
            }
        }
    }
    // Present the view controller in the Live View window
    PlaygroundPage.current.liveView = MyViewController()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多