NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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
                       .frame(maxWidth: .infinity)
                        .background(alternateRows(on: item) ? .gray.opacity(0.5) : .white)
    func alternateRows(on string: String) -> Bool {
        if let index = myArray.firstIndex(where: { $0 == string }) {
            if index % 2 == 0 {
                return true
        return false


Did you try adding the alignment parameter to frame?

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


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.


Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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.