尺寸适合 SwiftUI 底板高度问题

问题描述 投票:0回答:1

我想制作适合 SwiftUI 底板的尺寸

struct ContentView: View {
    @State var presentSheet: Bool = false
    
    var body: some View {
        Button("Tap me") {
            presentSheet.toggle()
        }
        .sheet(isPresented: $presentSheet) {
            BottomView()
        }
    }
}

struct BottomView: View {
    @State var detentHeight: CGFloat = 0
    
    var body: some View {
        Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.")
        .padding(40)
        .fixedSize(horizontal: false, vertical: true)
        .readHeight()
        .onPreferenceChange(HeightPreferenceKey.self) { height in
            detentHeight = height
        }
        .presentationDetents([.height(detentHeight)])
    }
}

我使用preferenceKey来计算纸张高度:

struct HeightPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = .zero

    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

private struct ReadHeightModifier: ViewModifier {
    private var sizeView: some View {
        GeometryReader { geometry in
            Color.clear.preference(key: HeightPreferenceKey.self, value: geometry.size.height)
        }
    }

    func body(content: Content) -> some View {
        content.overlay(sizeView)
    }
}

extension View {
    func readHeight() -> some View {
        self
            .modifier(ReadHeightModifier())
    }
}

一切工作正常,除了当我将应用程序放在后台并再次重新打开它时,工作表高度回到 0

有什么办法可以解决这个问题吗?

ios swift swiftui bottom-sheet
1个回答
0
投票

你可以试试这个 您需要从您显示的视图中设置高度和宽度

struct ContentView: View {
    @State var presentSheet: Bool = false
       
      
    var body: some View {
        VStack {
            Button("TEST") {
                presentSheet.toggle()
                
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .sheet(isPresented: $presentSheet) {
            BottomView()
        }       
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.