Having trouble adjusting the size of my frame to be the full width of the screen in my vstack in Card struct.
What can I do to make the cards full size, so I can adjust based on screen size?
struct ContentView: View {
var body: some View {
VStack{
ScrollView(.horizontal, showsIndicators: false){
HStack{
ForEach(0..<14){i in
Card().padding(.leading)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Card: View {
var body: some View {
GeometryReader{r in
VStack(alignment: .leading){
Color.red
}.frame(width: r.size.width, height: r.size.height/1.5).cornerRadius(20).padding(.leading)
}
}
Welcome to Stackoverflow!
I suppose you want your cards with a width equal to the screen size, and want it to be in a scrollView like in the screenshot. If so, read on...
You're in the right path. But framing the Card is best to be put when creating them, not when setting up its body.
struct ContentView: View {
var body: some View {
VStack{
GeometryReader{r in
ScrollView(.horizontal, showsIndicators: false){
HStack{
ForEach(0..<14) { i in
Card(color: Color.init(UIColor.random())).frame(width: r.size.width, height: r.size.height/1.5, alignment: .center)
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Card: View {
var color: Color
var body: some View {
GeometryReader{r in
self.color
}
}
}
For a bonus, let's use a random color.
extension UIColor {
static func random() -> UIColor {
func random() -> CGFloat { return .random(in:0...1) }
return UIColor(red: random(),
green: random(),
blue: random(),
alpha: 1.0)
}
}

That happened because you were using GeometryReader on the wrong view, try with this and check the result:
import SwiftUI
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false){
HStack{
ForEach(0..<14){ _ in
Card()
.frame(width: geometry.size.width, height: geometry.size.height/1.5)
.padding(.leading)
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Card: View {
var body: some View {
GeometryReader{r in
VStack(alignment: .leading){
Color.red
}.cornerRadius(20)
.padding(.leading)
}
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With