I have asked this question on stack overflow. You may read it there, because I have included 2 GIFs that illustrates the problem.
I am building a custom segmented control. This is the code that I have written.
Code Block struct SegmentedControl: View { private var items: [String] = ["One", "Two", "Three"] @Namespace var animation:Namespace.ID @State var selected: String = "One" var body: some View { ScrollView(.horizontal) { HStack { ForEach(items, id: \.self) { item in Button(action: { withAnimation(.spring()){ self.selected = item } }) { Text(item) .font(Font.subheadline.weight(.medium)) .foregroundColor(selected == item ? .white : .accentColor) .padding(.horizontal, 25) .padding(.vertical, 10) .background(zStack(item: item)) } } } .padding() } } private func zStack(item: String) -> some View { ZStack{ if selected == item { Color.accentColor .clipShape(Capsule()) .matchedGeometryEffect(id: "Tab", in: animation) } else { Color(.gray) .clipShape(Capsule()) }} } }
A control is Blue when it is selected.
However, sometimes if you navigate back and forth very fast, the Color.accentColor disappears
Info, It is easier to test it on a physical device rather than a simulator.