我正在将一个视图作为子视图添加到当前视图底部的UIViewController
中。我可以使用Alpha进行淡入淡出的动画,但我想像键盘弹出一样将其显示为幻灯片。
let popup: UIView = ..
popup.alpha = 0.0
self.view.addSubView(popup)
UIView.animate(withDuration: 0.3, animations: {
popup.alpha = 1.0
}) { _ in
}
如何对此进行动画处理?
答案 0 :(得分: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
}
假设视图位于屏幕底部,则将视图向下平移等于其高度的量,然后将变换动画化回其身份,即原始位置。
答案 1 :(得分:0)
要仅通过添加子视图来实现淡入淡出效果,请尝试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()