【问题标题】:Start animation once a UIView appeared on screen一旦 UIView 出现在屏幕上,就开始动画
【发布时间】:2016-04-04 09:31:54
【问题描述】:

我有一个自定义 UIView,我想在用户点击按钮后覆盖屏幕。它有点模拟自定义视图。自定义 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)

在警报视图中:

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()
    }
}

}

【问题讨论】:

    标签: swift uiview uiviewanimation


    【解决方案1】:

    我建议您通过以下方法之一调用您的 animate() 函数:

    • willMoveToSuperview:
    • didMoveToSuperview

    UIView 的这些方法可以根据需要跟踪当前视图在视图层次结构中的移动。

    参考:UIView class

    【讨论】:

    • 谢谢,我将使用 didMoveToSuperView。但这不是解决方案。解决方案是在动画关闭之前添加另一个 view.setNeedsDisplay() 调用。
    • 对不起,我的意思是调用 layoutIfNeeded()。
    【解决方案2】:

    您的最终约束值不在动画闭包中。试试这个:

    func animate() {
        // move the notification up 
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.notificationBottomConstraint.constant = 0
            self.view.setNeedsDisplay()
        }
    }
    

    【讨论】:

    • 它不需要在动画闭包内。也可以在外面工作。
    猜你喜欢
    • 2017-07-13
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多