SwiftUI:在 NavigationView 中嵌入父视图时不会调用 PreferenceKey

问题描述

DynamicScalingView一个带有两个按钮的子视图,使用 preferencekey

设计为具有相等的宽度和高度

问题:DynamicScalingView 嵌入到 NavigationView 中时,它不再适应 intrinsic增加其框架大小。没有导航的当前实现工作正常,但想了解如何在嵌入 NavigationView

解决此问题
  • 在示例视图中取消注释 NavigationView 以重现问题
  • DynamicScalingView 应适应动态字体大小并增加其框架大小,保持按钮之间的等宽和高度约束。

XCode 12.2 和 iOS 14.2

struct SampleView: View {
    var body: some View {
        GeometryReader { gr in
            //NavigationView {
                ScrollView {
                    vstack {
                        // fills whatever space is left
                        Spacer()
                            .foregroundColor(.clear)

                        // view should fit with intrinsic content size
                        DynamicScalingView()
                            .padding(.horizontal,20)
                            .border(Color.blue,width: 1)
                    }
                    .padding(.bottom,20)
                    .border(Color.red,width: 1)
                    .frame(minHeight: gr.size.height)
                    .navigationBarHidden(true)
                }
        //  }
        }
    }

    struct DynamicScalingView: View {
        @State private var labelHeight = CGFloat.zero

        var body: some View {
            HStack {
                Button(action: {},label: {
                    Text("Some Text Some Text Some Text")
                        .padding(.horizontal,2)
                })
                    .foregroundColor(Color.white)
                    .padding(.vertical)
                    .frame(minWidth: 0,maxWidth: .infinity)
                    .frame(minHeight: labelHeight)
                    .background(Color.blue)
                    .cornerRadius(8)
                    .fixedSize(horizontal: false,vertical: true)
                    .background(GeometryReader {
                        Color.clear
                            .preference(
                                key: ViewHeightKey.self,value: $0.frame(in: .local).size.height
                            )
                    })

                Button(action: {},label: {
                    Text("Some Text")
                        .padding(.horizontal,value: $0.frame(in: .local).size.height
                            )
                    })
            }
            .onPreferenceChange(ViewHeightKey.self) {
                self.labelHeight = $0
            }
        }
    }

    struct ViewHeightKey: PreferenceKey {
        static var defaultValue: CGFloat { 0 }
        static func reduce(value: inout Value,nextValue: () -> Value) {
            value = max(value,nextValue())
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)