我在加载视图控制器后显示一些自定义视图。像横幅一样,我正在展示自定义视图。我通过获取nib文件和已定义的元素来创建该视图。它的加载很好,但是,我想在加载自定义视图时添加一些动画。
我尝试了以下代码,但没有工作。
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "NotificationBannerView", bundle: nil)
let objects = nib.instantiate(withOwner: nil, options: nil)
notificationView = objects.first as! NotificationBannerView
UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut, animations: {
self.notificationView.layoutIfNeeded()
self.view.addSubview(self.notificationView)
}, completion: nil)
}
我没有使用autoresizing(Size classes)类。
有任何建议可以实现这一目标吗?谢谢!
答案 0 :(得分:2)
首先,您要将视图添加为子视图:
self.view.addSubview(self.notificationView)
然后,你想添加一些约束来定义它应该在哪里,例如:
notificationView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
notificationView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
notificationView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
notificationView.topAnchor.constraint(equalTo: self.view.topAnchor),
notificationView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
])
然后你想添加动画,例如淡入:
self.notificationView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut, animations: {
self.notificationView.alpha = 1
}, completion: nil)
旁注:
如果您想使用autolayout将其设置为来自其他地方的视图,那么在将其添加为子视图并激活初始约束集后,请调用:
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
然后定义一组新的约束,这些约束将在激活它们之后再次定义其最终帧:
self.view.setNeedsLayout()
最后在动画块中使用(这将为notificationView
的新帧设置动画效果):
UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
答案 1 :(得分:0)
let nib = UINib(nibName: "NotificationBannerView", bundle: nil)
let objects = nib.instantiate(withOwner: nil, options: nil)
notificationView = objects.first as! NotificationBannerView
notificationView.frame = CGRect(x:-100; y:0; width: 100; height:100)
self.view.addSubView(notificationView)
UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseIn, animations: {
notificationView.frame = CGRect(x:10; y:20; width: 100; height:100)
}, completion: nil)
这将显示左侧带动画的视图。
答案 2 :(得分:0)
最后,我找到了解决方案。 我希望这可能有助于未来。
override func viewDidAppear(_ animated: Bool) {
//animation
UIView.animate(withDuration: 5, delay: 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.notificationView.transform = CGAffineTransform(scaleX: 1, y: 0.5)
self.notificationView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/360)
self.notificationView.frame = CGRect(x: 2, y: self.pageControl.frame.maxY, width:self.view.frame.width-2, height:130)
}, completion: nil)
}