Last active
December 19, 2025 09:03
-
-
Save brownsoo/f67d919952d0a7045cefb1508efdcaad to your computer and use it in GitHub Desktop.
UIView 크기만큼 미리보기 제공
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// UIView 크기만큼 미리보기 제공 | |
| import SwiftUI | |
| public struct CompactPreview<V: UIView>: View { | |
| @State private var parentSize: CGSize? | |
| @State private var foundSize: CGSize? | |
| /// UIView 빌더 | |
| let builder: () -> V | |
| /// 가로를 상위에 채울껀지 | |
| let fillingWidth: Bool | |
| public init(parentSize: CGSize? = nil, fillParent: Bool = true, builder: @escaping () -> V) { | |
| self.parentSize = parentSize | |
| self.fillingWidth = fillParent | |
| self.builder = builder | |
| } | |
| public var body: some View { | |
| ZStack { | |
| if let parentWidth = parentSize?.width { | |
| CompactUIWrapper(width: parentWidth, fillWidth: fillingWidth, sizeUpdate: { size in | |
| DispatchQueue.main.async { | |
| self.foundSize = size | |
| } | |
| }, builder: builder) | |
| } | |
| } | |
| .frame(maxWidth: foundSize?.width ?? parentSize?.width ?? .infinity, | |
| maxHeight: foundSize?.height ?? parentSize?.height ?? .infinity) // 크기 제한 .. | |
| .background( | |
| GeometryReader { geometry in | |
| Color.clear.onAppear { | |
| if foundSize != nil { return } | |
| DispatchQueue.main.async { | |
| parentSize = geometry.size // 상위 크기 구하기... | |
| } | |
| } | |
| } | |
| ) | |
| } | |
| } | |
| struct CompactUIWrapper<V: UIView>: UIViewRepresentable { | |
| var width: CGFloat | |
| var fillWidth: Bool | |
| var sizeUpdate: (CGSize) -> Void | |
| let builder: () -> V | |
| public func makeUIView(context: Context) -> some UIView { | |
| let view = builder() | |
| view.translatesAutoresizingMaskIntoConstraints = false | |
| // 적합한 크기 계산 | |
| let size = view.systemLayoutSizeFitting(CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)) | |
| debugPrint("CompactUIWrapper \(width) => \(size)") | |
| self.sizeUpdate(CGSize(width: fillWidth ? width : size.width, height: size.height)) | |
| // 크기 설정 | |
| let h = view.heightAnchor.constraint(equalToConstant: size.height) | |
| h.priority = .defaultHigh | |
| h.isActive = true | |
| let w = view.widthAnchor.constraint(equalToConstant: fillWidth ? width : size.width) | |
| w.priority = .defaultHigh | |
| w.isActive = true | |
| view.setContentCompressionResistancePriority(.required, for: .vertical) | |
| view.setContentHuggingPriority(.required, for: .vertical) | |
| return view | |
| } | |
| public func updateUIView(_ uiView: UIViewType, context: Context) { | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment