Using convert(_:to:) method in swift

I want to convert a rectangle from another collectionview (cellContentCollectionView) to an equal rectangle in my root view controller.

The instance method used to do this is convert(_:to:), however I am having trouble setting the frame of the UIView in the root view controllers frame.

Here's what I have so far...

cellContentCollectionView?.convert((playerLayer?.frame)!, to: fullScreenPlayerView)

cellContentCollectionView is the collectionView that it's located in. Which happens to be in a collectionViewCell.

Any suggestions?

2 answers

  • answered 2017-06-17 19:20 rob mayoff

    You didn't explain the exact relationship between cellContentCollectionView and playerLayer, so I'm going to assume the worst: that playerLayer is not a subview of cellContentCollectionView.

    I also suspect that playerLayer is not actually a view at all, but is a CALayer. That's okay, because on iOS, a view's frame is always its layer.frame, so we can just deal with the layers.

    The frame of a layer is in the geometry of its superlayer. So you must ask its superlayer to convert its frame. But, if the layer isn't transformed, you could instead ask the layer to convert its own bounds instead.

    If you intend to use the resulting rectangle as the frame of a target layer, you must convert to the target layer's superlayer. You can't just convert to the target layer's geometry and set the target layer's bounds, because that doesn't update the position of the target layer.

    Thus I think you want to write this:

    if
        let playerLayer = playerLayer,
        let fullScreenPlayerSuper = fullScreenPlayerView.layer.superlayer
    {
        let frame = playerLayer.convert(playerLayer.bounds, to: fullScreenPlayerSuper)
        fullScreenPlayerView.frame = frame
    }
    

  • answered 2017-06-17 19:20 Infinity James

    This is how I would do it, assuming that playerLayer is a UIView.

    guard let playerLayer = playerLayer, superview = playerLayer.superview else { return }
    
    fullScreenPlayerView.convert(playerLayer.frame, from: superview)