Skip to content

Instantly share code, notes, and snippets.

@yuraist
Last active May 16, 2021 11:50
Show Gist options
  • Save yuraist/b67e68420e15aaba070f14144de5e664 to your computer and use it in GitHub Desktop.
Save yuraist/b67e68420e15aaba070f14144de5e664 to your computer and use it in GitHub Desktop.
View isn't updating with zIndex in ForEach
import SwiftUI
struct TestItemView: View {
@State var dragAmount = CGSize.zero
let letter: String
var body: some View {
Image(systemName: "\(letter).square")
.offset(dragAmount)
// .zIndex(dragAmount == .zero ? 0 : 1)
.gesture(
DragGesture()
.onChanged({
self.dragAmount = CGSize(width: $0.translation.width,
height: $0.translation.height)
})
.onEnded({ _ in
self.dragAmount = .zero
})
)
}
}
struct TestView: View {
@State var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
var body: some View {
HStack {
ForEach(0..<10) { number in
// Letters doesn't update inside TextItemView after updating in the onAppear method
// if there is the zStack modifier on the TestItemView object
TestItemView(letter: self.letters[number])
}
}
.onAppear {
self.letters = (0...10).map { _ in self.randomLetter() }
}
}
private func randomLetter() -> String {
String("ABCDEFGHIJKLMMNOPQRSTUVWXYZ".randomElement()!)
.lowercased()
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
@nasru
Copy link

nasru commented May 16, 2021

Hello there
I am having the same problem now. Did you find any solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment