Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Last active September 10, 2021 16:56
Show Gist options
  • Save VAndrJ/d6c1042127dab09684a45e7ef2864bb2 to your computer and use it in GitHub Desktop.
Save VAndrJ/d6c1042127dab09684a45e7ef2864bb2 to your computer and use it in GitHub Desktop.
//
// Created by Volodymyr Andriienko on 18.05.2021.
// Copyright © 2021 VAndrJ. All rights reserved.
//
#if DEBUG
#if canImport(SwiftUI)
import SwiftUI
@available (iOS 13.0, *)
struct Representable: UIViewRepresentable {
let view: UIView
func makeUIView(context: Context) -> UIView {
return view
}
func updateUIView(_ uiView: UIView, context: Context) {}
}
enum RepresentablePreviewLayout {
case fixed(CGSize)
case auto
case frameInherited
case undefined
case flexibleWidth(height: CGFloat)
case flexibleHeight(width: CGFloat)
}
@available (iOS 13.0, *)
extension UIView {
func sRepresentation(layout: RepresentablePreviewLayout) -> AnyView {
switch layout {
case let .fixed(size):
return Representable(view: self)
.frame(width: size.width, height: size.height, alignment: .topLeading)
.previewLayout(.sizeThatFits)
.anyView
case .auto:
let size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return Representable(view: self)
.frame(width: size.width, height: size.height)
.previewLayout(.sizeThatFits)
.anyView
case .frameInherited:
return Representable(view: self)
.frame(width: frame.width, height: frame.height)
.previewLayout(.sizeThatFits)
.anyView
case .undefined:
return Representable(view: self)
.anyView
case let .flexibleWidth(height):
frame.size = CGSize(width: UIView.layoutFittingExpandedSize.width, height: height)
setNeedsLayout()
layoutIfNeeded()
let size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return Representable(view: self)
.frame(width: size.width, height: height, alignment: .topLeading)
.previewLayout(.sizeThatFits)
.anyView
case let .flexibleHeight(width):
frame.size = CGSize(width: width, height: UIView.layoutFittingExpandedSize.height)
setNeedsLayout()
layoutIfNeeded()
let size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return Representable(view: self)
.frame(width: width, height: size.height, alignment: .topLeading)
.previewLayout(.sizeThatFits)
.anyView
}
}
}
@available (iOS 13.0, *)
extension View {
var anyView: AnyView {
return AnyView(self)
}
}
#endif
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment