NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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
    }
}

1      

Did you try adding the alignment parameter to frame?

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

1      

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.

1      

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it now

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

Reply to this topic…

You need to create an account or log in to reply.

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.