我有一个自定义 UIView,我想在用户点击按钮后覆盖屏幕。它有点模拟自定义 View 。自定义 UIView 中有一个子 UIView,它应该从底部(首先隐藏)到其正常位置(在底部可见)进行动画处理。我遇到的问题是,layoutSubviews 似乎不是开始制作动画的好地方。正确的地方在哪里?类似于 viewDidAppear 但适用于 UIViews。
在 UIViewController 中:
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()
}
}
}
最佳答案
我建议您从以下方法之一调用 animate()
函数:
willMoveToSuperview:
didMoveToSuperview
UIView 的这些方法根据需要跟踪 View 层次结构中当前 View 的移动。
引用: UIView class
关于swift - 一旦 UIView 出现在屏幕上就开始动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36398985/