【问题标题】:Using convert(_:to:) method in swift在 swift 中使用 convert(_:to:) 方法
【发布时间】:2017-11-20 08:52:37
【问题描述】:

我想在我的根视图控制器中将另一个集合视图 (cellContentCollectionView) 中的矩形转换为相等的矩形。

用于执行此操作的实例方法是 convert(_:to:),但是我无法在根视图控制器框架中设置 UIView 的框架。

这是我目前所拥有的......

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

cellContentCollectionView 是它所在的 collectionView。它恰好在 collectionViewCell 中。

有什么建议吗?

【问题讨论】:

  • convert 方法返回一个新的 CGRect 你必须使用它,let newFrame = cellContentCollectionView?.convert((playerLayer?.frame)!, to: fullScreenPlayerView)
  • 那么第二个参数 [to View: UIView?] 有什么意义呢?我有点困惑
  • 是转换的目标视图,该视图是您需要放置矩形的视图,您需要将playerLayer?.framecellContentCollectionView 转换为fullScreenPlayerView 坐标系
  • 好吧,这是有道理的。当我设置 fullScreenPlayerView.bounds = (newFrame) 时,我仍然遇到问题!我收到错误的指令错误,因为它发现为零。
  • 起点和终点两个视图必须在同一个视图树内,否则此方法可以返回 nil

标签: ios swift uiview uicollectionview uicollectionviewcell


【解决方案1】:

您没有解释cellContentCollectionViewplayerLayer 之间的确切关系,所以我将假设最坏的情况:playerLayer 不是cellContentCollectionView 的子视图。

我还怀疑playerLayer 实际上根本不是视图,而是CALayer。没关系,因为在 iOS 上,视图的frame 始终是它的layer.frame,所以我们可以只处理层。

层的frame 位于其超层的几何结构中。所以你必须要求它的超级层转换它的frame。但是,如果图层未转换,您可以改为要求图层转换其自己的bounds

如果您打算将生成的矩形用作目标层的框架,则必须转换为目标层的超层。您不能只转换为目标图层的几何体并设置目标图层的bounds,因为这不会更新目标图层的position

所以我想你想写这个:

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

【讨论】:

  • 这不会产生任何错误,但是该代码产生的帧是 0,0,0,0
  • print(playerLayer.bounds) 输出是什么?
  • 另外,playerLayer 是一个 AVPlayerLayer,它位于 AVPlayer 和 UIView 之上
  • print(playerLayer.bounds) 产生零
  • 那么playerLayer本身必须为nil。
【解决方案2】:

假设playerLayerUIView,我就是这样做的。

guard let playerLayer = playerLayer, superview = playerLayer.superview else { return }

fullScreenPlayerView.convert(playerLayer.frame, from: superview)

【讨论】:

  • playerLayer 是一个 AVPlayerLayer 我引用它的原因是因为无论如何我都需要它的视觉输出。但是它被屏蔽为 UIView,所以我将尝试将 UIView 与您的代码一起使用
  • 您的代码不会产生任何结果。就好像它在产生 nil,但它并没有说出来。
猜你喜欢
  • 1970-01-01
  • 2015-04-15
  • 2015-07-22
  • 2019-06-15
  • 2022-12-02
  • 2022-12-16
  • 1970-01-01
  • 2013-10-10
相关资源
最近更新 更多