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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.