Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// ContentView.swift
// OrView
//
// Created by Chris Eidhof on 07.11.19.
// Copyright © 2019 Chris Eidhof. All rights reserved.
//
import SwiftUI
struct SizePreference: PreferenceKey {
static let defaultValue: CGSize? = nil
static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) {
value = value ?? nextValue()
}
}
extension View {
func sizePreference() -> some View {
return self.background(GeometryReader { proxy in
Color.clear.preference(key: SizePreference.self, value: proxy.size)
})
}
}
struct OrView<L: View, R: View>: View {
var left: L
var right: R
@State var leftWidth: CGFloat? = nil
var body: some View {
GeometryReader { proxy in
self.left
.sizePreference()
.onPreferenceChange(SizePreference.self) { value in
self.leftWidth = value?.width
}.hidden()
if self.leftWidth != nil && self.leftWidth! > proxy.size.width {
self.right
} else {
self.left
}
}.transformPreference(SizePreference.self, { $0 = nil })
}
}
extension View {
// Pick `self` (unless it doesn't fit, then pick `other`).
func or<Other: View>(_ other: Other) -> some View {
return OrView(left: self, right: other)
}
}
struct ContentView: View {
@State var fontSize: CGFloat = 20
var body: some View {
VStack {
Text("Hello, World This Is Some Text!")
.font(.system(size: fontSize))
.fixedSize()
.or(Text("HI"))
Slider(value: $fontSize, in: 10...40)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.