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

Time:03-30

I am looking for how to align items in a list horizontally, where the items start at the last item, or on the right edge, and go left from there.

For example, with a list of 1-20, I'd be looking to show items 1-5 off the left edge of the screen, with item 20 being the right-most item, right on the edge of the screen. An image of this can be shown below (it is not the solution running, but rather a contrived image to show the desired effect).

enter image description here

How can I do this in SwiftUI?

An HStack will simply center itself horizontally. HStack doesn't seem to have a horizontal alignment that I can control.

An HStack in a scrollview allows me to reach the right-most item, but still starts at the first item, or the left-most edge of the list.

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?
        }
    }
}

CodePudding user response:

If I properly understand question looks like you need 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)
         }
      }
   }
}
  • Related