0

Not sure how to setup bindings from the init function.

struct VideoPlayerView: View {
    let url: URL

    @State private var videoPos: Double = 0
    @State private var videoDuration: Double = 0
    @State private var seeking = false

    private var videoView: VideoView

    init(url: URL) {
        self.url = url
        self.videoView = VideoView(
            url: self.url,
            videoPos: $videoPos,
            videoDuration: $videoDuration,
            seeking: $seeking
        )
    }

    func togglePlay () {
        self.videoView.play()
    }

    var body: some View {
        ZStack {
            videoView
            Button(action: togglePlay) {
                Text("Test")
            }
        }
    }
}

I'm getting the following error on the 3 lines with the '$'.

Variable 'self.videoView' used before being initialized

1 Answer 1

1

SwiftUI view have to be used within view builder (ie. initiated in some body). So, use instead the following

struct VideoPlayerView: View {
    let url: URL

    @State private var videoPos: Double = 0
    @State private var videoDuration: Double = 0
    @State private var seeking = false

    private var videoView: VideoView { // << computable property
        VideoView(                     //    will be created in body
            url: self.url,
            videoPos: $videoPos,
            videoDuration: $videoDuration,
            seeking: $seeking
        )
    }

    init(url: URL) {
        self.url = url
    }

    func togglePlay () {
        self.videoView.play()
    }

    var body: some View {
        ZStack {
            videoView
            Button(action: togglePlay) {
                Text("Test")
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

This almost works.... The issue is any time the body need updates a new VideoView is created.
@Justin808, this is expected SwiftUI behaviour, actually swift behaviour... in the same way as ZStack is created, Button, Text, etc. Just make creation light.
Then how to I call a method on a view without getting a new view? I want to tell the video to play, not create a whole new video view.
@Justin808, this is SwiftUI - it is reactive - you don't send methods to views, instead change states and views are refreshed on those changes reacting as needed.
Its not a state... its a function... to do something.... I want to do an action, not update a parameter
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.