nonamorando
nonamorando

Reputation: 1605

SwiftUI - ScrollView: onChange -> scrollTo cuts off text

Currently, I have a ScrollView with this code:

ScrollView {
    ScrollViewReader { scrollView in
        VStack {
            ForEach(messages, id: \.id) { message in
                MessageView(message)
            }
            MessageInput()
        }
        .onChange(of: messages.count) { _ in
            scrollView.scrollTo(messages.last.id)
        }
        .onAppear { scrollView.scrollTo(messages.last.id) }
    }
}

.onAppear() works as intended, giving this view: .onAppear Image However, when I send a new message and .onChange is called, I get this: .onChange appearance

MessageView() does have padding, but I don't see how that would affect it only .onChange and not .onAppear.

How can I move the view down so that the message input box is included?

Upvotes: 1

Views: 2175

Answers (1)

Asperi
Asperi

Reputation: 257711

If you really want input be inside scroller then, probably, you need something like the following

ScrollView {
    ScrollViewReader { scrollView in
        VStack {
            ForEach(messages, id: \.id) { message in
                MessageView(message)
            }
            MessageInput().id("input")
        }
        .onChange(of: messages.count) { _ in
            scrollView.scrollTo("input", anchor: .bottom)
        }
        .onAppear { 
            scrollView.scrollTo("input", anchor: .bottom)
        }
    }
}

Upvotes: 2

Related Questions