Swift 在屏幕上出现UIView后启动动画
我有一个自定义UIView,我想在用户点击按钮后覆盖屏幕。它模拟了一种自定义视图。自定义UIView中有一个子UIView,它应该从底部(首先隐藏)到其正常位置(在底部可见)设置动画。我遇到的问题是,似乎layoutSubviews不是开始制作动画的好地方。正确的地点在哪里?如果不是UIView,则会出现类似ViewDid的内容 在UIViewController中:Swift 在屏幕上出现UIView后启动动画,swift,uiview,uiviewanimation,Swift,Uiview,Uiviewanimation,我有一个自定义UIView,我想在用户点击按钮后覆盖屏幕。它模拟了一种自定义视图。自定义UIView中有一个子UIView,它应该从底部(首先隐藏)到其正常位置(在底部可见)设置动画。我遇到的问题是,似乎layoutSubviews不是开始制作动画的好地方。正确的地点在哪里?如果不是UIView,则会出现类似ViewDid的内容 在UIViewController中: let rect: CGRect = CGRectMake(0, 0, view.bounds.size.width, view
let rect: CGRect = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height)
let alertView = AlertView(frame: rect)
view.addSubview(alertView)
在AlertView中:
import UIKit
class AlertView: UIView {
let nibName = "AlertView"
let animationDuration = 0.5
var view: UIView!
@IBOutlet weak var notificationView: UIView!
@IBOutlet weak var notificationBottomConstraint: NSLayoutConstraint!
override init(frame: CGRect) {
super.init(frame: frame)
viewSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
viewSetup()
}
override func didAddSubview(subview: UIView) {
super.didAddSubview(subview)
}
func viewSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// move the notification view offscreen
notificationBottomConstraint.constant = -notificationView.frame.size.height
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiateWithOwner(self, options: nil)[0] as! UIView
}
override func layoutSubviews() {
super.layoutSubviews()
print("layoutSubviews")
animate()
}
func animate() {
// move the notification up
self.notificationBottomConstraint.constant = 0
UIView.animateWithDuration(animationDuration) { () -> Void in
self.view.setNeedsDisplay()
}
}
}最终约束值不在动画闭包中。试试这个:
func animate() {
// move the notification up
UIView.animateWithDuration(animationDuration) { () -> Void in
self.notificationBottomConstraint.constant = 0
self.view.setNeedsDisplay()
}
}
我建议您通过以下方法之一调用
animate()
函数:
willMoveToSuperview:
didmovetoserview
参考:它不需要在动画闭包中。也在外面工作。谢谢,我将使用didMoveToSuperView。但这并不是解决办法。解决方案是在动画结束之前添加另一个view.setNeedsDisplay()调用。对不起,我的意思是调用layoutifneedd()。