如何在视图的右边缘对齐和锚定 SwiftUI 水平列表?

How to align and anchor SwiftUI horizontal list at right edge of view?

我正在寻找如何水平对齐列表中的项目,项目从最后一个项目开始,或从右边缘开始,然后从那里向左移动。

例如,对于 1-20 的列表,我希望在屏幕的左边缘显示项目 1-5,项目 20 是最右边的项目,就在屏幕的边缘屏幕。下面可以显示一张图片(这不是解决方案 运行,而是一个人为的图片来显示所需的效果)。

我如何在 SwiftUI 中执行此操作?

HStack 将简单地水平居中。 HStack 似乎没有我可以控制的水平对齐方式。

滚动视图中的 HStack 允许我到达最右边的项目,但仍然从第一个项目或列表的最左边开始。

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Divider()
            // the HStack just tries to fit everything within the width of the view,
            // without anything going "offscreen"
            HStack(spacing: 10) {
                ForEach(1..<21) { index in
                    Text("\(index)")
                }
                Spacer()
            }
            Divider()
            // placing the HStack within a ScrollView does allow elements to go offscreen,
            // but the list starts at 1 and goes offscreen at 16  on the right
            // I am looking for how to "anchor" the list on the right edge instead,
            // with elements 1 through 5 being displayed off the left edge of the screen,
            // and the right-most element being 20, directly on the right edge of the screen
            ScrollView(.horizontal) {
                HStack(spacing: 10) {
                    ForEach(1..<21) { index in
                        Text("\(index)")
                    }
                }
            }
            .frame(height: 100)
            Divider()
            // are there any other ways to achieve my desired effect?
        }
    }
}

如果我正确理解了问题,那么您似乎需要 ScrollViewReader:

// Define array for your label
var entries = Array(0...20)
    
ScrollView(.horizontal) {
   ScrollViewReader { reader in
      HStack(spacing: 10) {
         ForEach(entries, id: \.self) { index in
            Text("\(index)")
         }.onAppear {
            // Here on appear scroll go to last element
            reader.scrollTo(entries.count - 1)
         }
      }
   }
}