I have a ZStack that I set the color to black and then add a VideoPlayer. When I rotate the device there are still flashes of white around the player. I have played with all sorts of ideas and background colors, foreground colors, opacity and nothing has worked. I just want the background to be black so it looks like a smooth rotation. Anybody have any suggestions or fixes? Here’s my code:
import Foundation
import SwiftUI
import AVKit
struct VideoDetail: View {
var videoIDString: String
var videoThumbURL: String
@State var player = AVPlayer()
var body: some View {
ZStack {
Color.black
.edgesIgnoringSafeArea(.all)
let videoURL: String = videoIDString
VideoPlayer(player: player)
//.frame(height: 200)
.edgesIgnoringSafeArea(.all)
.onAppear {
player = AVPlayer(url: URL(string: videoURL)!)
player.play()
}
.onDisappear {
player.pause()
}
}
.navigationBarHidden(true)
.background(Color.black.edgesIgnoringSafeArea(.all))
}
}
3
Answers
I was having the same issue and came across a solution: you can set the background color of the hosting window’s root view controller’s view. You don’t have direct access to this within SwiftUI, so in order to do this you can use a method described in this answer.
Just copy the
withHostingWindow
View extension includingHostingWindowFinder
somewhere and use the following code in your view to set the background color to black:After this, the white corners when rotating should be gone!
I feel your pain. This is a SwiftUI bug. The way that SwiftUI currently works is that it contains your view tree within a UIKit view. For the most part SwiftUI and UIKit cooperate with one another pretty well, but one particular area that struggles seems to be synchronising UIKit and SwiftUI animations.
Therefore, when the device rotates, it’s actually UIKit driving the animation, so SwiftUI has to make a best guess of where it might be on the animation curve but its guess is pretty poor.
The best thing we can do right now is file feedback. Duplicated bug reports are how Apple prioritise what to work on, so the more bug reports from everyone the better. It doesn’t have to be long. Title it something like ‘SwiftUI animation artefacts on device rotation’, and write ‘Duplicate of FB10376122’ for the description to reference an existing report on the same topic.
Anyway, in the meantime, we can at least grab the UIKit view of the enclosing window and set the background colour on there instead. This workaround is limited as 1) it doesn’t change the apparent ‘jumpiness’ of the above mentioned synchronisation between the UIKit and SwiftUI animations, and 2) will only help if your background is a block colour.
That said, here’s a
WindowGroup
replacement and view modifier pair that ties together this workaround to play as nicely as possible with the rest of SwiftUI.Example usage:
To use, copy the contents below into a file named
StyledWindowGroup.swift
and add to your project:Just add