简体   繁体   中英

SwiftUI: Horizontally Align Views Inside a List

I'm trying to get items inside a list to line up in a specific way.

List {
    HStack {
        Text("1.")
        Text("Item 1")
    }

    HStack {
        Text("Item 2")
    }
}

That winds up looking like this:

1. Item 1
Item 2

What I'd like is to line up, in this example, "Item 1" and "Item 2":

1.  Item 1
    Item 2

That is, the "item" parts all line up whether they have a list marker or not, or if they have list markers of different lengths (number 1. lines up with 100.)

I tried making a custom alignment guide as seen here but these don't seem to be respected inside a List --- it works fine if I make the AlignmentGuide and put it all in a VStack , but I need list behavior.

(I could fake this by getting rid of the HStacks and doing Text("1.\tItem 1") and Text("\tItem 2") . The tab stops would make everything line up, but I need to apply different formatting to the list marker and the list item (bolding, color, etc.), so they need to be discrete Text elements.)

Any ideas would be appreciated.

在此处输入图像描述

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            HStack {
                Text("1.").frame(width: 20.0, height: nil, alignment: .leading)
                Text("Item 1")
            }
            HStack {
                Text("Item 2")
                .padding(EdgeInsets(top: 0, leading: 28, bottom: 0, trailing: 0))
            }
            HStack {
                Text("2.").frame(width: 20.0, height: nil, alignment: .leading)
                Text("Item 3")
            }
            HStack {
                Text("Item 4")
                .padding(EdgeInsets(top: 0, leading: 28, bottom: 0, trailing: 0))
            }
        }
    }
}

** Updated **

Hope this is closer to what you are looking for.

By specifying a frame around the leading value, you can control its size so it should work for your need to modify the text value.

It should also be possible to calculate values for the purpose of setting the frame and padding, but these hard coded values should achieve the immediate effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM