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())
}
}
}
}
}
}
}
}
@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