SwiftUI bring stack element to foreground

Viewed 132

I would like to use a drag and drop function in my application but have still the problem, that I don't know how to bring the first VStack element to foreground. Thankful for every help.

import SwiftUI

struct GameView: View {
@State private var text = "Element to be in foreground"
@State private var offset = CGSize.zero

var body: some View {
    HStack(){
        VStack(){
            Text(text)
        }
        .frame(maxWidth: 100)
        .frame(height: 100)
        .background(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)), Color(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1))]), startPoint: .top, endPoint: .bottom))
        .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
        .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 20)
        .contentShape(Rectangle())
        .offset(y: offset.height)
        .offset(x: offset.width)
        .gesture(DragGesture()
                .onChanged { val in
                    self.offset = val.translation
                }
                .onEnded { val in
                    self.offset = .zero
                }
        )
        VStack(){
            Text("Text which is currently in foreground")
        }
    }
}
}

struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView()
        }
 }
1 Answers

Order of views in one container can be changed by zIndex (which is by default zero for all), as

var body: some View {
    HStack(){
        VStack(){
            Text(text)
        }
        .frame(maxWidth: 100)
        .frame(height: 100)
        .background(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)), Color(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1))]), startPoint: .top, endPoint: .bottom))
        .clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
        .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 20)
        .contentShape(Rectangle())
        .offset(y: offset.height)
        .offset(x: offset.width)
        .gesture(DragGesture()
                .onChanged { val in
                    self.offset = val.translation
                }
                .onEnded { val in
                    self.offset = .zero
                }
        )
        .zIndex(1)         // << here !!

        VStack(){
            Text("Text which is currently in foreground")
        }
    }
}
Related