Created
July 17, 2020 02:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()) | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey sorry for the delay.
I've decided to go with some other approaches and wait for the new swiftUI release :)