Skip to content

Instantly share code, notes, and snippets.

@bmc08gt
Last active March 29, 2024 20:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmc08gt/3225d6ef670add10f6fa56f206a98290 to your computer and use it in GitHub Desktop.
Save bmc08gt/3225d6ef670add10f6fa56f206a98290 to your computer and use it in GitHub Desktop.
Compose UI component in SwiftUI that respects intrinsic sizing
private fun measuredViewController(
onMeasured: (Double, Double) -> Unit,
content: @Composable () -> Unit,
): UIViewController = ComposeUIViewController {
Box(
modifier = Modifier.onGloballyPositioned {
onMeasured(it.size.width.toDouble(), it.size.height.toDouble())
},
) {
content()
}
}
fun _Badge(
count: Int,
onMeasured: (Double, Double) -> Unit,
): UIViewController = measuredViewController(onMeasured = onMeasured) {
Badge(count = count)
}
struct MeasuredView<Content: View>: View {
@State public var measuredWidth: CGFloat = 1000.0
@State var measuredHeight: CGFloat = 1000.0
var content: (Binding<CGFloat>, Binding<CGFloat>) -> Content
init(@ViewBuilder content: @escaping (Binding<CGFloat>, Binding<CGFloat>) -> Content) { self.content = content }
var body: some View {
content($measuredWidth, $measuredHeight)
.frame(width: measuredWidth / UIScreen.main.scale, height: measuredHeight / UIScreen.main.scale)
}
}
private struct BadgeCountViewControllerRepresentable : UIViewControllerRepresentable {
@State public var count: Int32
@Binding var measuredWidth: CGFloat
@Binding var measuredHeight: CGFloat
public func makeUIViewController(context: Context) -> UIViewController {
ComponentsKt._Badge(count: count) { w, h in
measuredWidth = CGFloat(truncating: w)
measuredHeight = CGFloat(truncating: h)
}
}
public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
}
public struct Badge: View {
let count: Int32
public var body: some View {
MeasuredView(
content: { w, h in
BadgeCountViewControllerRepresentable(
count: count,
measuredWidth: w,
measuredHeight: h
)
}
)
}
}
HStack {
Badge(count: 3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment