应用约束后迅速获得视野

时间:2019-02-25 13:04:56

标签: swift autolayout

我有一个.xib文件,其中包含一个我想用来播放视频文件的视图。该视图具有配置其大小和位置的约束。现在,我需要获取这些内容以配置我的视频播放器:

let slide1: OnboardingSlide = Bundle.main.loadNibNamed("OnboardingSlide", owner: self, options: nil)?.first as! OnboardingSlide
if let path = Bundle.main.path(forResource: "Onboarding_01", ofType: "mp4") {
    let videoURL = URL(fileURLWithPath: path)
    slide1.videoPlayer = AVPlayer(url: videoURL)
    let playerLayer = AVPlayerLayer(player: slide1.videoPlayer)
    playerLayer.frame = slide1.videoView.bounds // <-- this does not work

    slide1.layer.addSublayer(playerLayer)
    slide1.videoPlayer?.play()

    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: slide1.videoPlayer?.currentItem, queue: .main) { _ in
        slide1.videoPlayer?.seek(to: CMTime(seconds: 0, preferredTimescale: 1))
        slide1.videoPlayer?.play()
    }
}

但是slide1.videoView.bounds仅在应用约束之前包含rect。我如何获得实际的尺寸和位置?

1 个答案:

答案 0 :(得分:0)

您可以尝试通过以下方式强制布局机计算大小和位置:

    setNeedsLayout()
    layoutIfNeeded()

例如:

    ...
    slide1.videoPlayer = AVPlayer(url: videoURL)
    let playerLayer = AVPlayerLayer(player: slide1.videoPlayer)
    setNeedsLayout()
    layoutIfNeeded()
    ...

或者只是尝试在layoutSubviews()

中捕获slide1.videoPlayer的适当大小