1

我正在 SwiftUI 中构建一个自定义 SegmentedPicker,其中选择器调整其大小以适合每个选择器项目的框架。我已经按照这篇文章(检查视图树PreferenceKey)的启发使用 s 来实现统一大小的项目,如下所示:

在此处输入图像描述

我认为我可以大大简化我的实现,并通过使用PreferencyKeys 来完全避免使用 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)
        
    }
}

任何想法如何解决这一问题?

4

1 回答 1

0

PreferenceKey当项目具有不同的帧大小时,我设法解决了使用 s 的选择器实现所遇到的所有动画问题。这并不能解决我对zIndex和 的问题.matchedGeometryEffect(),所以我不会接受我自己的答案,但我会将它作为参考发布,以防将来有人需要它。

编码:

public struct PKPicker: View {
    @Binding var selection: Int
    @State private var frames: [CGRect] = []
    let items: [String]
    
    public init(
        selection: Binding<Int>,
        items: [String])
    {
        self._selection = selection
        self._frames = State(wrappedValue: Array<CGRect>(repeating: CGRect(),
                                                         count: items.count))
        self.items = items
    }
    
    public var body: some View {
        ZStack(alignment: .topLeading) {
            selector
            HStack {
                ForEach(items.indices)  { index in
                    itemView(for: index)
                        
                }
            }
        }
        .onPreferenceChange(PKPickerItemPreferenceKey.self) { preferences in
            preferences.forEach { frames[$0.id] = $0.frame }
        }
        .coordinateSpace(name: "picker2")
        
    }
    
    var selector: some View {
        Color.gray.opacity(0.25).clipShape(Capsule())
            .frame(width: frames[selection].size.width,
                   height: frames[selection].size.height)
            .offset(x: frames[selection].minX, y: frames[selection].minY)
    }
    
    func itemView(for index: Int) -> some View {
        Text(items[index])
            .fixedSize()
            .padding(7)
            .foregroundColor(isSelected(index) ? .black : .gray)
            .font( .caption)
            .onTapGesture { selection = index }
            .background(PKPickerItemPreferenceSetter(id: index))
            
    }
    
    func isSelected(_ index: Int) -> Bool {
        index == selection
    }
}

struct PKPickerItemPreferenceData: Equatable {
    let id: Int
    let frame: CGRect
}

struct PKPickerItemPreferenceKey: PreferenceKey {
    typealias Value = [PKPickerItemPreferenceData]

    static var defaultValue: [PKPickerItemPreferenceData] = []
    
    static func reduce(
        value: inout [PKPickerItemPreferenceData],
        nextValue: () -> [PKPickerItemPreferenceData])
    {
        value.append(contentsOf: nextValue())
    }
}

struct PKPickerItemPreferenceSetter: View {
    let id: Int
    let coordinateSpace = CoordinateSpace.named("picker2")
    
    var body: some View {
        GeometryReader { geometry in
            Color.clear
                .preference(key: PKPickerItemPreferenceKey.self,
                            value: [PKPickerItemPreferenceData(
                                        id: id, frame: geometry.frame(in: coordinateSpace))])
        }
    }
}

而在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 {
    PKPicker(selection: $selection.animation(.easeInOut), items: pickerItems)
        .padding(7)
        .background(Color.gray.opacity(0.10).clipShape(Capsule()))
        .padding(5)
    
}

结果:

在此处输入图像描述

于 2021-03-10T19:05:05.770 回答