'How to Align GeometryReader in SwiftUI?
I am trying to create a View using GeometryReader and then use it in ContentView, however no matter what changes I make , I just cannot make the View created with GeometryReader align to centre, can any one please suggest where I need to make changes, thanks
My View using GeometryReader
import SwiftUI
struct DiceView: View {
let randomNumber = Int.random(in: 400...1000)
@Binding var randomRoll: Int
var body: some View {
GeometryReader { geo in
Text("\(randomRoll)")
.font(.title)
.padding(.horizontal)
.background(
Rectangle()
.foregroundColor(Color(hue: min(1, geo.frame(in: .global).minY/CGFloat(randomNumber) ), saturation: 1, brightness: 1))
.frame(minWidth: 120, minHeight: 120)
.cornerRadius(10))
}
.frame(height: 150)
}
}
Where I am using it
import SwiftUI
struct DiceRoller: View {
let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
]
@State private var number = 9
@State private var type = (1...10).map { _ in Int.random(in: 1...10)}
@State var total = [Int]()
var body: some View {
LazyVGrid(columns: columns, spacing: 10) {
ForEach(0..<number, id: \.self) { item in
DiceView(randomRoll: $type[item])
.onAppear {
total.append(type[item])
}
}
Text("\(total.reduce(0, +))")
}
.padding(.horizontal)
}
}
What I see on screen
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

