From b6da67934d8d9feb5dcc78841db7c31a6fde09d5 Mon Sep 17 00:00:00 2001 From: Ryo Aoyama Date: Fri, 25 Oct 2019 00:02:42 +0900 Subject: [PATCH] Fix for conform with both reference size and fitting size. --- .../ComponentSwiftUISupport.swift | 60 +++++++++++++------ 1 file changed, 41 insertions(+), 19 deletions(-) diff --git a/Sources/SwiftUISupport/ComponentSwiftUISupport.swift b/Sources/SwiftUISupport/ComponentSwiftUISupport.swift index 63a6929..8e28cd7 100644 --- a/Sources/SwiftUISupport/ComponentSwiftUISupport.swift +++ b/Sources/SwiftUISupport/ComponentSwiftUISupport.swift @@ -22,21 +22,10 @@ private struct ComponentView: View { } var body: some View { - let size: CGSize? = bounds.flatMap { bounds in - if let referenceSize = component.referenceSize(in: bounds) { - return referenceSize - } - - return proxy.uiView?.systemLayoutSizeFitting( - bounds.size, - withHorizontalFittingPriority: .required, - verticalFittingPriority: .fittingSizeLevel - ) - } - + let size = preferredSize() return ComponentRepresenting(component: component, proxy: proxy) - .frame(height: size?.height) - .frame(idealWidth: size?.width) + .frame(idealWidth: size.idealWidth) + .frame(width: size.fixedWidth, height: size.fixedHeight) .onAppear { self.proxy.uiView?.contentWillDisplay() } .onDisappear { self.proxy.uiView?.contentDidEndDisplay() } .background(GeometryReader { geometry in @@ -46,6 +35,39 @@ private struct ComponentView: View { } } +@available(iOS 13.0, *) +extension ComponentView { + struct Size { + var idealWidth: CGFloat? + var fixedWidth: CGFloat? + var fixedHeight: CGFloat? + } + + func preferredSize() -> Size { + if let bounds = bounds, let referenceSize = component.referenceSize(in: bounds) { + return Size( + fixedWidth: referenceSize.width, + fixedHeight: referenceSize.height + ) + } + else if let bounds = bounds, let uiView = proxy.uiView { + let fittingSize = uiView.systemLayoutSizeFitting( + bounds.size, + withHorizontalFittingPriority: .required, + verticalFittingPriority: .fittingSizeLevel + ) + + return Size( + idealWidth: fittingSize.width, + fixedHeight: fittingSize.height + ) + } + else { + return Size() + } + } +} + private struct BoundsPreferenceKey: PreferenceKey { static func reduce(value: inout CGRect?, nextValue: () -> CGRect?) {} } @@ -65,16 +87,16 @@ private struct ComponentRepresenting: UIViewRepresentable { } private final class UIComponentView: UIView, ComponentRenderable { - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } } private final class ComponentViewProxy {