skip to Main Content

I have a horizontal scroll user experience with a ScrollView and an HStack. I wanted to figure out a way to realize that the user has reached the end of the HStack.

To accomplish that, I used this solution (open to better solutions)

The functionality works as expected and I can realize when the user is at the end of the scrollview.

This is my code so far

var body: some View {
    ScrollView(.horizontal) {
        LazyHStack(spacing: 10) {
            content
            endOfListView
        }
    }
}

private var endOfListView: some View {
    Color.clear
        .frame(width: .zero, height: .zero)
        .onAppear {
            didReachEnd = true
        }
}

The issue I am having now is that even the endOfListView has a frame of .zero, an additional 10 spacing is added because of the spacing set in the HStack constructor.

I tried to add this .padding(.leading, -10) to the endOfListView, however, that didn’t help and the spacing was still there.

I also came across a similar problem but doesn’t concern the spacing so I couldn’t apply it.

Is there a way override the spacing for specific elements within an HStack or an alternative way to solve this ?

2

Answers


  1. If the LazyHStack is adding unwanted spacing before your sentinel view, just move the sentinel view out of it! You should be able to put your endOfListView marker directly within the ScrollView:

        ScrollView(.horizontal) {
            LazyHStack(spacing: 10) {
                content
            }
            endOfListView
        }
    

    It still comes “after” all of the content in the LazyHStack, so it should still serve its purpose of allowing you to run some code when the user has reached the end.

    Login or Signup to reply.
  2. Try putting your detector view in the background of the content instead:

    LazyHStack(spacing: 10) {
        content
            .background(alignment: .trailing) {
                endOfListView
            }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search