简体   繁体   English

SwiftUI:水平对齐列表内的视图

[英]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":在这个例子中,我想要排列“Item 1”和“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.)也就是说,无论是否有列表标记,或者是否有不同长度的列表标记(数字 1. 与 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.我尝试制作自定义 alignment 指南,如此处所示,但这些似乎在List中没有得到尊重——如果我制作AlignmentGuide并将其全部放在VStack中,它工作正常,但我需要列表行为。

(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.) (我可以通过摆脱HStacks并执行Text("1.\tItem 1")Text("\tItem 2")来伪造这一点。制表位会使所有内容对齐,但我需要应用不同的格式列表标记和列表项(粗体、颜色等),因此它们需要是离散的Text元素。)

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.也应该可以计算用于设置框架和填充的值,但这些硬编码值应该能达到立竿见影的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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