ios 从UIViewcontroller显示带有高度配件内容大小的SwiftUIView工作表

drkbr07n  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(109)

我需要从UIViewController显示一个包含SwiftUI视图的工作表,但工作表的高度必须与SwiftUI视图内容的高度相匹配。
我知道有可能为工作表的高度指定自定义止动器,但我想知道在从UIViewController显示SwiftUI视图时是否有可能获得内容大小的高度?
到目前为止,我已经尝试在SwiftUI视图中的GeometryReader的帮助下获取内容大小,但没有得到任何结果。
以下是我的代码,其中展示了SwiftUI视图以供参考:

func presentSwiftUIPageSheet() {
    let swiftUIView = SwiftUIView()
    let hostingController = UIHostingController(rootView: swiftUIView)

    hostingController.modalPresentationStyle = .pageSheet      
    hostingController.isModalInPresentation = false
    hostingController.sheetPresentationController?.detents = [.medium(), .large()]

    present(hostingController, animated: true)
}

字符串
任何建议将不胜感激!

tag5nh1u

tag5nh1u1#

对于SwiftUI只有代码,这里有一个问题和答案:Make sheet the exact size of the content inside基于此,iOS 16.0+用于从UIViewcontroller进行演示的解决方案将是:

func presentSwiftUIPageSheet() {
    var sheetHeight = CGFloat.zero
    let swiftUIView = SwiftUIView()
        .readSize { sheetHeight = $0.height }

    let hostingController = UIHostingController(rootView: swiftUIView)
    hostingController.modalPresentationStyle = .pageSheet
    hostingController.isModalInPresentation = false
    hostingController.sheetPresentationController?.detents = [.custom { _ in 0 },
                                                              .large()]
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        hostingController.sheetPresentationController?.animateChanges {
            hostingController.sheetPresentationController?.detents = [.custom { _ in sheetHeight },
                                                                      .large()]
        }
    }
    present(hostingController, animated: true)
}

字符串
使用SwiftUI扩展:

private struct SizePreferenceKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
}

extension View {

    func readSize(onChange: @escaping (CGSize) -> Void) -> some View {
        background(
            GeometryReader { proxy in
                Color.clear
                    .preference(key: SizePreferenceKey.self, value: proxy.size)
            }
        ).onPreferenceChange(SizePreferenceKey.self, perform: onChange)
    }
}

相关问题