Swiftui Scrollview scroll to bottom of list - swift

I'm trying to make my view scroll to the bottom of the item list every time a new item is added.
This is my code, can someone help please?
ScrollView(.vertical, showsIndicators: false) {
ScrollViewReader{ value in
VStack() {
ForEach(0..<self.count, id:\.self) {
Text("item \($0)")
}
}.onChange(of: self.data.sampleCount, perform: value.scrollTo(-1))
}
}

We need to give id for views which in ScrollView we want to scroll to.
Here is a demo of solution. Tested with Xcode 12.1 / iOS 14.1
struct DemoView: View {
#State private var data = [String]()
var body: some View {
VStack {
Button("Add") { data.append("Data \(data.count + 1)")}
.padding().border(Color.blue)
ScrollView(.vertical, showsIndicators: false) {
ScrollViewReader{ sr in
VStack {
ForEach(self.data.indices, id:\.self) {
Text("item \($0)")
.padding().id($0) // << give id
}
}.onChange(of: self.data.count) { count in
withAnimation {
sr.scrollTo(count - 1) // << scroll to view with id
}
}
}
}
}
}
}

You can add an EmptyView item in the bottom of list
ScrollView(.vertical, showsIndicators: false) {
ScrollViewReader{ value in
VStack() {
ForEach(0..<self.count, id:\.self) {
Text("item \($0)")
}
Spacer()
.id("anID") //You can use any type of value
}.onChange(of: self.data.sampleCount, perform: { count in
value.scrollTo("anID")
})
}

Here is my example/solution.
var scrollView : some View {
ScrollView(.vertical) {
ScrollViewReader { scrollView in
ForEach(self.messagesStore.messages) { msg in
VStack {
OutgoingPlainMessageView() {
Text(msg.message).padding(.all, 20)
.foregroundColor(Color.textColorPrimary)
.background(Color.colorPrimary)
}.listRowBackground(Color.backgroundColorList)
Spacer()
}
// 1. First important thing is to use .id
//as identity of the view
.id(msg.id)
.padding(.leading, 10).padding(.trailing, 10)
}
// 2. Second important thing is that we are going to implement //onChange closure for scrollTarget change,
//and scroll to last message id
.onChange(of: scrollTarget) { target in
withAnimation {
scrollView.scrollTo(target, anchor: .bottom)
}
}
// 3. Third important thing is that we are going to implement //onChange closure for keyboardHeight change, and scroll to same //scrollTarget to bottom.
.onChange(of: keyboardHeight){ target in
if(nil != scrollTarget){
withAnimation {
scrollView.scrollTo(scrollTarget, anchor: .bottom)
}
}
}
//4. Last thing is to add onReceive clojure, that will add an action to perform when this ScrollView detects data emitted by the given publisher, in our case messages array.
// This is the place where our scrollTarget is updating.
.onReceive(self.messagesStore.$messages) { messages in
scrollView.scrollTo(messages.last!.id, anchor: .bottom)
self.scrollTarget = messages.last!.id
}
}
}
}
Also take a look at my article on medium.
https://mehobega.medium.com/auto-scrollview-using-swiftui-and-combine-framework-b3e40bb1a99f

Related

SwiftUI: Call a function of a programmatically created view

I am trying to make a SwiftUI ScrollView scroll to a certain point in an abstracted view when a button is pressed in a view which is calling the abstracted view programmatically. Here is my code:
struct AbstractedView: View {
#Namespace var view2ID
var body: some View {
ScrollView {
VStack {
View1()
View2()
.id(view2ID)
View3()
}
}
}
func scrollToView2(_ proxy: ScrollViewProxy) {
proxy.scrollTo(view2ID, anchor: .topTrailing)
}
}
As you can see, when scrollToView2() is called (in a ScrollViewReader), the AbstractedView scrolls to view2ID. I am creating a number of AbstractedView's programmatically in a different View:
struct HigherView: View {
var numAbstractedViewsToMake: Int
var body: some View {
VStack {
HStack {
ForEach (0..<numAbstractedViewsToMake, id: \.self) { _ in
AbstractedView()
}
}
Text("button")
.onTapGesture {
/* call each AbstractedView.scrollToView2()
}
}
}
}
If I stored these views in an array in a struct inside my HigherView with a ScrollViewReader for each AbstractedView would that work? I feel as though there has to be a nicer way to achieve this, I just have no clue how to do it. I am new to Swift so thank you for any help.
P.S. I have heard about UIKit but I don't know anything about it, is this the right time to be using that?
Using the comments from #Asperi and #jnpdx, I was able to come up with a more powerful solution than I needed:
class ScrollToModel: ObservableObject {
enum Action {
case end
case top
}
#Published var direction: Action? = nil
}
struct HigherView: View {
#StateObject var vm = ScrollToModel()
var numAbstractedViewsToMake: Int
var body: some View {
VStack {
HStack {
Button(action: { vm.direction = .top }) { // < here
Image(systemName: "arrow.up.to.line")
.padding(.horizontal)
}
Button(action: { vm.direction = .end }) { // << here
Image(systemName: "arrow.down.to.line")
.padding(.horizontal)
}
}
Divider()
HStack {
ForEach(0..<numAbstractedViewsToMake, id: \.self) { _ in
ScrollToModelView(vm: vm)
}
}
}
}
}
struct AbstractedView: View {
#ObservedObject var vm: ScrollToModel
let items = (0..<200).map { $0 } // this is his demo
var body: some View {
VStack {
ScrollViewReader { sp in
ScrollView {
LazyVStack { // this bit can be changed accordingly
ForEach(items, id: \.self) { item in
VStack(alignment: .leading) {
Text("Item \(item)").id(item)
Divider()
}.frame(maxWidth: .infinity).padding(.horizontal)
}
}.onReceive(vm.$direction) { action in
guard !items.isEmpty else { return }
withAnimation {
switch action {
case .top:
sp.scrollTo(items.first!, anchor: .top)
case .end:
sp.scrollTo(items.last!, anchor: .bottom)
default:
return
}
}
}
}
}
}
}
}
Thank you both!

LazyVStack - row onAppear is called early

I have a LazyVStack, with lots of rows. Code:
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack {
ForEach(0 ..< 100) { i in
Text("Item: \(i + 1)")
.onAppear {
print("Appeared:", i + 1)
}
}
}
}
}
}
Only about 40 rows are visible on the screen initially, yet onAppear is triggered for 77 rows. Why is this, why is it called before it is actually visible on the screen? I don't see why SwiftUI would have to 'preload' them.
Is there a way to fix this, or if this is intended, how can I accurately know the last visible item (accepting varying row heights)?
Edit
The documentation for LazyVStack states:
The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.
So this must be a bug then, I presume?
By words from the documentation, onAppear shouldn't be like this:
The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.
However, if you are having problems getting this to work properly, see my solution below.
Although I am unsure why the rows onAppears are triggered early, I have created a workaround solution. This reads the geometry of the scroll view bounds and the individual view to track, compares them, and sets whether it is visible or not.
In this example, the isVisible property changes when the top edge of the last item is visible in the scroll view's bounds. This may not be when it is visible on screen, due to safe area, but you can change this to your needs.
Code:
struct ContentView: View {
#State private var isVisible = false
var body: some View {
GeometryReader { geo in
ScrollView {
LazyVStack {
ForEach(0 ..< 100) { i in
Text("Item: \(i + 1)")
.background(tracker(index: i))
}
}
}
.onPreferenceChange(TrackerKey.self) { edge in
let isVisible = edge < geo.frame(in: .global).maxY
if isVisible != self.isVisible {
self.isVisible = isVisible
print("Now visible:", isVisible ? "yes" : "no")
}
}
}
}
#ViewBuilder private func tracker(index: Int) -> some View {
if index == 99 {
GeometryReader { geo in
Color.clear.preference(
key: TrackerKey.self,
value: geo.frame(in: .global).minY
)
}
}
}
}
struct TrackerKey: PreferenceKey {
static let defaultValue: CGFloat = .greatestFiniteMagnitude
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
It works as per my comments above.
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack {
ForEach(0 ..< 100) { i in
Text("Item: \(i + 1)")
.id(i)
.frame(width: 100, height: 100)
.padding()
.onAppear { print("Appeared:", i + 1) }
}
}
}
}
}
It seems incredible but just adding a GeometryReader containing your ScrollView would resolve the issue
GeometryReader { _ in
ScrollView(.vertical, showsIndicators: false) {
LazyVStack(spacing: 14) {
Text("Items")
LazyVStack(spacing: 16) {
ForEach(viewModel.data, id: \.id) { data in
MediaRowView(data: data)
.onAppear {
print(data.title, "item appeared")
}
}
if viewModel.state == .loading {
ProgressView()
}
}
}
.padding(.horizontal, 16)
}
}

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:
However, when I send a new message and .onChange is called, I get this:
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?
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)
}
}
}

Sticky footer in List SwiftUI

I am trying to implement a sticky footer in a List View in SwiftUI
It doesn't seem to operate the same as the header per say. This is an example of a sticky header implementation
List {
ForEach(0..<10) { index in
Section(header: Text("Hello")) {
ForEach(0..<2) { index2 in
VStack {
Rectangle().frame(height: 600).backgroundColor(Color.blue)
}
}
}.listRowInsets(EdgeInsets())
}
}
This above gives a sticky header situation. Although, once I change Section(header: ... to Section(footer:... it doesn't seem to be sticky anymore, it's simply places at the end of the row.
A more explicit reference
List {
ForEach(0..<10) { index in
Section(footer: Text("Hello")) {
ForEach(0..<2) { index2 in
VStack {
Rectangle().frame(height: 600).backgroundColor(Color.blue)
}
}
}.listRowInsets(EdgeInsets())
}
}
Does anyone have any solutions for this?
With the latest on SwiftUI (2) we now have access to a few more API's
For starters we can use a LazyVStack with a ScrollView to give us pretty good performance, we can then use the pinnedViews API to specify in an array which supplementary view we want to pin or make sticky. We can then use the Section view which wraps our content and specify either a footer or header.
** This code is working as of Xcode beta 2 **
As for using this in a List I'm not too sure, will be interesting to see the performance with List vs Lazy...
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack(spacing: 10, pinnedViews: [.sectionFooters]) {
ForEach(0..<20, id: \.self) { index in
Section(footer: FooterView(index: index)) {
ForEach(0..<6) { _ in
Rectangle().fill(Color.red).frame(height: 100).id(UUID())
}
}
}
}
}
}
}
struct FooterView: View {
let index: Int
var body: some View {
VStack {
Text("Footer \(index)").padding(5)
}.background(RoundedRectangle(cornerRadius: 4.0).foregroundColor(.green))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can use overlay on the List:
struct ContentView: View {
#State private var selectedTab = 0
var body: some View {
TabView(selection: $selectedTab) {
VStack {
List {
ForEach(0..<20, id: \.self) { _ in
Section {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
}
}
.listStyle(InsetGroupedListStyle())
.overlay(
VStack {
Spacer()
Text("Updated at: 5:26 AM")
.font(.footnote)
.foregroundColor(.secondary)
.frame(maxWidth: .infinity)
}
)
}
.tabItem {
Label("First", systemImage: "alarm")
}
Text("Content 2")
.tabItem {
Label("Second", systemImage: "calendar")
}
}
}
}

How to animate view appearance?

I have a custom view. It used as a cell in a List view. I would like to animate appearance of a Group subview on quote.expanded = true (e.g. fading).
.animation(.default) modifier does not work.
struct QuoteView: View {
var quote : QuoteDataModel
var body: some View {
VStack(alignment: .leading, spacing: 5) {
Text(quote.latin)
.font(.title)
if quote.expanded {
Group() {
Divider()
Text(quote.russian).font(.body)
}
}
}
}
}
The following code animates for me. Note that animation inside a list, while still probably better than no animation, can still look kind of weird. This is because the height of the list rows themselves do not animate, and snap to their final height, while the view inside the row does animate. This is a SwiftUI issue, and there's not anything you can do about it for now other than file feedback that this behavior doesn't look great.
struct StackOverflowTests: View {
#State private var array = [QuoteDataModel(), QuoteDataModel(), QuoteDataModel()]
var body: some View {
List {
ForEach(array.indices, id: \.self) { index in
QuoteView(quote: self.array[index])
.onTapGesture { self.array[index].expanded.toggle() }
}
}
}
}
struct QuoteView: View {
var quote : QuoteDataModel
var body: some View {
VStack(alignment: .leading, spacing: 5) {
Text(quote.latin)
.font(.title)
if quote.expanded {
Group() {
Divider()
Text(quote.russian).font(.body)
}
}
}
.animation(.default)
}
}
Use a Transition to animate the view Appearance:
https://developer.apple.com/tutorials/swiftui/animating-views-and-transitions
https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-and-remove-views-with-a-transition
try this....but you will see, that there are still other problems, because the text is left aligned...
var body: some View {
VStack(alignment: .leading, spacing: 5) {
Button("Tap me") {
withAnimation() {
self.expanded.toggle()
if self.expanded {
self.opacity = 1
} else {
self.opacity = 0
}
}
}
Text("aha")
.font(.title)
if expanded {
Group() {
Divider()
Text("oho").font(.body)
}.opacity(opacity)
}
}
}