【问题标题】:How access frame of a toView object in custom animation如何在自定义动画中访问 toView 对象的框架
【发布时间】:2016-11-15 17:18:23
【问题描述】:

想做一个iOS主屏文件夹之类的动画,要知道“文件夹”最终位置的frame:

我正在使用自定义过渡,这里是动画文件的代码:

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

    }
}

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

我遵循this 教程,用 Swift 编写代码

那么,我怎样才能正确访问该属性?

【问题讨论】:

    标签: ios swift animation frame


    【解决方案1】:

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

    toVC.view.layoutIfNeeded()
    

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

    【讨论】:

    • 我想访问toViewC.containerView.frame,这是“文件夹”的矩形,正如你在屏幕截图中看到的那样。我已删除转换,但它不起作用...
    • 但是如果我将false 发送到completeTransition 我会返回我的第一个视图
    • 呃,我在这个答案上为你做得很糟糕。对不起,我也错了。
    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2019-03-02
    • 2019-09-30
    • 2016-07-03
    相关资源
    最近更新 更多