2

I have a list of messages that are stored in an array and then displayed to the screen via a loop, which is within a ScrollView. What i want is when the view is loaded the scroll view is scrolled all the way to the bottom, which i attempted to do with the scrollTo function, however the scroll view stayed in the same position no matter what value i passed into it. Can someone help point me in the right direction on how to do this.

struct MessageList2: View {
    @Binding var messages: [String]

    var body: some View {
        ScrollViewReader { value in
            ScrollView() {
                
                VStack(alignment: .leading) {
                    ForEach(0..<messages.count, id: \.self) { index in
                        Text(messages[index])
                    }
                    
                }
                .onAppear{
                    value.scrollTo(messages.count)
                }
                
            }
        }
        
    
    
    }
    
    }

Note the 'messages array receives value from another function and works just fine

I tried following examples online that showed how to use the ScrollView and scrollTo() and tried to implement it myself however the view stayed the same. Im assuming that im using the function wrong. I also tried adding a .id(index) under Text() but that didnt seem to work.

1 Answer 1

1

This is an off-by-one error. Note the id's you are assigning to each items are the same the index of the elements. The max index that can appear in messages is messages.count - 1, which means the max possible id is messages.count - 1.

So instead of scrollTo(messages.count), you probably meant to scrollTo(messages.count - 1).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.