UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Aligning Text Views

Forums > SwiftUI

I'm trying to create an alternating list of text views, one with a light-gray background and one with a white background similar to a spreadsheet. I can get it to appear the way I want using maxWidth: .infinity but then everything is centered which I don't want. If I get rid of maxWidth: .infinity, evertyhing is left-aligned, which I want, but then the gray background doesn't extend across, which I do want. I have to be missing something simple here, but honestly, I don't totally understand how VStacks and HStacks align things. I get that one is vertical and one is horizontal but they don't seem to behave the way I think they should. Any help would be appreciated.

struct ContentView: View {
    let myArray = [
        "1. Placeholder text for item #1 in the array myArray.",
        "2. Item #2.",
        "3. Item #3.",
        "4. Placeholder text for item #4 in the array myArray.",
        "5. Placeholder text for item #5 in the array myArray.",
        "6. Item #6.",
        "7. Item #7.",
        "8. Item #8.",
        "9. Item #9.",
        "10. Placeholder text for item #10 in the array myArray."
    ]

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                ForEach(myArray, id: \.self) { item in
                    Text(item)
                       .frame(maxWidth: .infinity)
                        .background(alternateRows(on: item) ? .gray.opacity(0.5) : .white)
                        .padding(0.5)
                }
            }
            .padding()
        }
    }
    func alternateRows(on string: String) -> Bool {
        if let index = myArray.firstIndex(where: { $0 == string }) {
            if index % 2 == 0 {
                return true
            }
        }
        return false
    }
}

2      

Did you try adding the alignment parameter to frame?

.frame(maxWidth: .infinity, alignment: .leading)

2      

Ya know, I thought I had tried that, but I tried so many different things, I might have done .frame(width: .infinity, alignment: .leading), which doesn't work. Thanks.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.