1

I'm trying to design a mixing desk for an iPad app using SwiftUI. I have an image for the background of the fader and will be using a slider stacked on top of it to change the volume. I have a View called faderView() which contains the image and the slider.

struct FaderView: View {
    @State var sliderValue: CGFloat = 0
    
    var body: some View {
        ZStack{
            //FaderBackground()
            Image("FaderBackground")
                .resizable()
                .scaledToFit()
                .cornerRadius(10)
                .padding()
            
            //Faderslider()
            GeometryReader { geo in
                HStack(alignment: .center) {
                    Slider(
                        value: $sliderValue,
                        in: 0...127,
                        step: 1.0
                    )
                    .frame(width: geo.size.height * 0.84)
                    .rotationEffect(.degrees(-90.0), anchor: .center)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
    }
}

This results in the following View which is exactly what I want (for now)

Desired View

If I then use a HStack to make multiple of these, the slider now moves to the right and I don't understand why. The code for just one is:

struct MixerView: View {
    var body: some View {
        HStack{
            FaderView()
        }
    }
}

Only 1 faderView()

struct MixerView: View {
    var body: some View {
        HStack{
            FaderView()
            FaderView()
        }
    }
}

2 faderView() where it is shifted

Any help with this would be greatly appreciated.

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Wpitchy
  • 97
  • 6
  • 1
    Use `border` to put borders around the image and slider and I believe you'll see what's happening. `GeometryReader` eagerly takes up all space allotted to it, so it's actually taking up half the screen in your bottom example. Constrain the width to the width of the image and go from there. – jnpdx Feb 22 '23 at 15:26
  • Thank you @jnpdx, that does help, I can see the issue. But I don't know how to fix it. The slider doesn't seem to be positioned in the centre of the view. How do I change this? – Wpitchy Feb 22 '23 at 15:44
  • @jnpdx Sorted it. Changing the frame width and height from .infinity to width of `GeometryReader` worked and centered it in the frame. Thank you! – Wpitchy Feb 22 '23 at 15:54

1 Answers1

2

Thanks to jnpdx, this has been solved. Changing frame maxHeight and maxWidth from .infinity to size of GeometryReader centered the slider in the frame

Original code:

.frame(maxWidth: .infinity, maxHeight: .infinity)

Changed code:

.frame(maxWidth: geo.size.width, maxHeight: geo.size.height)

Mixer with sliders in correct place

Wpitchy
  • 97
  • 6