Iām not going to spend too much talking about this here, because we talked about it on the show. Here is the awesome example code that Matt Waller from Weird Swift meetup sent to us to show how we could use GeometryReader to easily change a stack orientation in SwiftUI.
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var objects = [1, 2, 3, 4, 5, 6]
@State var horizontal = true
func switchOrientation()
var body: some View {
VStack {
Button(action: switchOrientation) {
Text("Switch orientation")
}
ZStack {
GeometryReader { proxy in
ForEach(self.objects, id: \.self) { index in
Text("\(index)")
.offset(self.offsetCalculator(size: proxy.size, index: index))
}
}
}
.animation(.default)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
func offsetCalculator(size: CGSize, index: Int) -> CGSize {
if horizontal {
let screenDivision = CGFloat(size.width / CGFloat(objects.count + 1))
let height: CGFloat = 0
let width = CGFloat(index) * screenDivision
return CGSize(width: width, height: height)
} else {
let screenDivision = CGFloat(size.height / CGFloat(objects.count + 1))
let height = CGFloat(index) * screenDivision
let width: CGFloat = 0
return CGSize(width: width, height: height)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View
}
PlaygroundPage.current.setLiveView(ContentView())