【问题标题】:How to make a copy of UIView with all layer properties?如何使用所有图层属性制作 UIView 的副本?
【发布时间】:2018-02-13 09:28:06
【问题描述】:

我正在为从初始屏幕呈现UINavigationController 进行自定义转换,我应该只为根视图控制器设置动画。我有一个UIStackView,里面有按钮。每个按钮和UIStackView 都有一个阴影和图层属性masksToBounds 设置为false。我为UINavigationController 编写了一个自定义动画师,我在animateTransition(using transitionContext: UIViewControllerContextTransitioning) 方法中制作了所有动画。当我为现有的UIStackView 设置动画时,我将它放入transitionContextcontainerView 中,当其他UIViewController 被推送时它并没有消失。如果我使用removeFromSuperView,它也会从我的rootViewController 中删除。我试着像这样复制UIStackView

let archive = NSKeyedArchiver.archivedData(withRootObject: toVC.buttonsStackView)
let buttonsStackViewCopy = NSKeyedUnarchiver.unarchiveObject(with: archive) as! UIStackView

但它不会复制图层的属性、字体等。

我也尝试像这样将图层渲染到 ImageContext 中:

UIGraphicsBeginImageContext(toVC.buttonsStackView.bounds.size)
let context = UIGraphicsGetCurrentContext()!
toVC.buttonsStackView.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let buttonsStackViewSnapshot = UIImageView(image: image)

第一个问题是像使用UIView 的简单快照一样剪切阴影。第二个问题是当我试图增加上下文大小时。阴影一切正常,但我无法正确计算 UIImageView.frame 来制作正确的动画。

是否有任何解决方案如何复制UIView 及其图层或如何将其从transitionContext.containerView 中删除而不删除它?还是我一般都做错了?

【问题讨论】:

    标签: ios swift uiview


    【解决方案1】:

    事实上,复制视图或其图层是错误的想法。我花了两天时间解决这个问题,但今天我只是将我的buttonsStackView.layer 作为子层添加到containerView.layer。然后,在 animate 方法的完成关闭中,我将它从 superLayer 中删除并添加到我的rootViewController.view.layer。效果很好。

    transitionContext.containerView.layer.addSublayer(buttonsStackViewSnapshot)

    UIView.animate(withDuration: duration,
                     animations: {
                       buttonsStackViewSnapshot.frame = finalButtonsFrame
    },
                     completion: { (finished) in
                       buttonsStackViewSnapshot.removeFromSuperlayer()
                       toVC.view.layer.addSublayer(buttonsStackViewSnapshot)
                       toVC.view.isHidden = false
                       transitionContext.completeTransition(finished)
    })
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 2015-11-26
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      相关资源
      最近更新 更多