Skip to content

Instantly share code, notes, and snippets.

@Mr-Perfection
Created July 17, 2020 02:20
Show Gist options
  • Save Mr-Perfection/937520af1818cd44714f59a4c0e184c4 to your computer and use it in GitHub Desktop.
Save Mr-Perfection/937520af1818cd44714f59a4c0e184c4 to your computer and use it in GitHub Desktop.
ScrollViewProxy didn't work when i use fetched data with observed object
// Repository
class BasePublicChatRepository {
@Published var publicChats = [PublicChat]()
}
// In repository, I load data from firebase. Like,
self.db.collection(self.publicChatsPath)
.whereField(...)
.getDocuments(completion: { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
self.publicChats = querySnapshot.documents.compactMap { document -> PublicChat? in
try? document.data(as: PublicChat.self)
}
} else {
print("error fetching publicChats: \(String(describing: error))")
}
})
// ViewModel
class PublicChatListVM: ObservableObject {
@Published var publicChatRepository: PublicChatRepository = Resolver.resolve()
...
init(...) {
publicChatRepository.$publicChats.map { publicChats in
publicChats.map { chat in
PublicChatCellVM(chat: chat, locationManager: locationManager)
}
}
.assign(to: \.joinedPublicChatCellVMs, on: self)
.store(in: &cancellables)
}
}
// View
struct PublicChatListView: View {
@ObservedObject var publicChatListVM: PublicChatListVM
init() {
self.publicChatListVM = PublicChatListVM()
...
}
var body: some View {
ScrollViewReader { scrollViewProxy in
VStack {
Button("Scroll to top") {
scrollViewProxy.scrollTo(0)
}
Button("Scroll to buttom") {
scrollViewProxy.scrollTo(itemCount-1)
}
ScrollView {
LazyVStack {
ForEach(self.publicChatListVM.joinedPublicChatCellVMs) { publicChatCellVM in
ZStack {
CellView(publicChatCellVM: publicChatCellVM)
NavigationLink(...)) {
EmptyView()
}
.buttonStyle(PlainButtonStyle())
}
}
}
}
}
}
}
}
@Amzd
Copy link

Amzd commented Jul 17, 2020

I'm pretty sure the ScrollViewReader has to be inside the ScrollView? I've never tested it outside. Also you have to add the ids with .id(_:scrollView:) which I don't see here.

@Mr-Perfection
Copy link
Author

Hey sorry for the delay.

I've decided to go with some other approaches and wait for the new swiftUI release :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment