我正在 SwiftUI 中构建一个自定义 SegmentedPicker,其中选择器调整其大小以适合每个选择器项目的框架。我已经按照这篇文章(检查视图树PreferenceKey
)的启发使用 s 来实现统一大小的项目,如下所示:
我认为我可以大大简化我的实现,并通过使用PreferencyKey
s 来完全避免使用 s .matchedGeometryEffect()
。我的想法是仅在选择该项目时在每个项目后面显示一个选择器,并使用.matchedGeometryEffect()
. 除了选择器将位于先前选择的项目前面的问题之外,几乎一切都在工作。我尝试显式设置zIndex
,但它似乎不影响结果:
编码:
struct MatchedGeometryPicker: View {
@Namespace private var animation
@Binding var selection: Int
let items: [String]
var body: some View {
HStack {
ForEach(items.indices) { index in
ZStack {
if isSelected(index) {
Color.gray.clipShape(Capsule())
.matchedGeometryEffect(id: "selector", in: animation)
.animation(.easeInOut)
.zIndex(0)
}
itemView(for: index)
.padding(7)
.zIndex(1)
}
.fixedSize()
}
}
.padding(7)
}
func itemView(for index: Int) -> some View {
Text(items[index])
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(isSelected(index) ? .black : .gray)
.font(.caption)
.onTapGesture { selection = index }
}
func isSelected(_ index: Int) -> Bool { selection == index }
}
并在ContentView
:
struct ContentView: View {
@State private var selection = 0
let pickerItems = [ "Item 1", "Long item 2", "Item 3", "Item 4", "Long item 5"]
var body: some View {
MatchedGeometryPicker(selection: $selection, items: pickerItems)
.background(Color.gray.opacity(0.10).clipShape(Capsule()))
.padding(.horizontal, 5)
}
}
任何想法如何解决这一问题?