Jack Vanderpump
Jack Vanderpump

Reputation: 486

Volume Slider within SwiftUI

How do you get a volume slider working in SwiftUI. Apple's tutorials provide help in regards to incorporating UIKit into a SwiftUI view (https://developer.apple.com/tutorials/swiftui/creating-and-combining-views#create-a-custom-image-view) but nothing that I can find on the volume slider. Below is the code I've got to this point largely taken from my Storyboard slider and adjusted, but it's not producing anything.

import SwiftUI
import UIKit
import MediaPlayer

struct VolumeView: UIViewRepresentable {


    func makeUIView(context: Context) -> UIView {
        UIView(frame: .init(x: 50, y: 100, width: 100, height: 100))
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        setupVolumeSlider()
    }


    func setupVolumeSlider() {
        var mpVolumeSlider: UISlider?
        let volumeParentView: UIView! = UIView()
        for subview in MPVolumeView().subviews {
            guard let volumeSlider = subview as? UISlider else { continue }
            mpVolumeSlider = volumeSlider
        }

        guard mpVolumeSlider != nil else { return }
        volumeParentView.addSubview(mpVolumeSlider!)
    }

}

Upvotes: 3

Views: 3153

Answers (1)

Jack Vanderpump
Jack Vanderpump

Reputation: 486

A lot easier than I was making it out to be in the end:

import SwiftUI
import MediaPlayer
import UIKit

struct HomeView: UIViewRepresentable {

    func makeUIView(context: Context) -> MPVolumeView {
        MPVolumeView(frame: .zero)
    }

    func updateUIView(_ view: MPVolumeView, context: Context) {

        }

}

Upvotes: 4

Related Questions