如何在自定义动画中访问toView对象的框架

时间:2016-07-13 08:21:19

标签: ios swift animation frame

我想制作一个类似iOS主屏幕文件夹的动画,我必须知道“文件夹”最终位置的框架:screen capture of the final view

我正在使用自定义转换,这是动画文件的代码:

class FolderAnimationController: NSObject, UIViewControllerAnimatedTransitioning {

    let duration    = 5.0
    var presenting  = true

    func transitionDuration(_ transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }

    func animateTransition(_ transitionContext: UIViewControllerContextTransitioning) {

        let containerView = transitionContext.containerView()
        let toViewC = transitionContext.viewController(forKey: UITransitionContextToViewControllerKey)! as! ProjectViewController
        let fromViewC = transitionContext.viewController(forKey: UITransitionContextFromViewControllerKey)!as! ViewController

        let cell : FolderCollectionViewCell = fromViewC.folderCollectionView.cellForItem(at: (fromViewC.folderCollectionView.indexPathsForSelectedItems()?.first!)!) as! FolderCollectionViewCell
        let cellSnapshot: UIView = cell.snapshotView(afterScreenUpdates: false)!
        let cellFrame = containerView.convert(cell.frame, from: cell.superview)
        cellSnapshot.frame = cellFrame
        cell.isHidden = true

        toViewC.view.frame = transitionContext.finalFrame(for: toViewC)
        toViewC.view.alpha = 0
        containerView.addSubview(toViewC.view)
        containerView.addSubview(cellSnapshot)

        UIView.animate(withDuration: duration, animations: {
            toViewC.view.alpha = 1.0

            let finalFrame = containerView.convert(toViewC.containerView.frame, from: toViewC.view)
            cellSnapshot.frame = finalFrame
            }) { (_) in
                cellSnapshot.removeFromSuperview()
                transitionContext.completeTransition(true)
        }

    }
}

一切正常,但let finalFrame = containerView.convert(toViewC.containerView.frame, from: toViewC.view)finalFrame值(是CGRect变量)设置为(origin = (x = 0, y = 0), size = (width = 0, height = 0))除外。

我已经按照this教程,在Swift中编写代码

那么,我该如何正确访问该属性?

1 个答案:

答案 0 :(得分:1)

框架是零rect,因为在您访问它时,视图的布局传递没有发生。设置toVC.view框后,添加以下行:

toVC.view.layoutIfNeeded()

如果您有兴趣,我已经写过关于在视图控制器转换here中使用快照的文章。