问题描述
我在尝试滚动到 ScrollView 顶部时遇到问题。我在 SCrollView 中使用了 ScrollViewReader,并使用 .onReceive() 我的 lazyvstack 订阅了视图模型中的 @PUlished scrollToTop 属性。我看到它正确接收了通知,但我的 Scroll 没有移到顶部。这是我的代码:
struct NewsList: View {
@Observedobject var viewmodel: NewsListviewmodel
@State var isDetailsViewShown = false
var body: some View {
NavigationView {
GeometryReader { geometry in
vstack {
if !viewmodel.isSearching {
TitleView(title: "News")
.frame(height: geometry.size.height / 11)
.frame(minWidth: 0,maxWidth: .infinity,minHeight: 0)
.padding(.horizontal,13)
.padding(.bottom,0)
}
SearchView(searchText: $viewmodel.searchText,isSearching: $viewmodel.isSearching)
.padding([.trailing,.leading,.bottom],13)
if !viewmodel.isSearching {
TabsView(selected: $viewmodel.selectedTab)
.padding(.horizontal,13)
}
ScrollView {
ScrollViewReader { reader in
Lazyvstack(spacing: 15) {
ForEach(articles.indices,id: \.self) { index in
NavigationLink(destination: DetailsNewsView(article: articles[index])) {
NewsCell(article: articles[index])
.onAppear {
checkActionForLastCell(index: index)
}
}.buttonStyle(FlatLinkStyle())
}
}.animation(nil)
.padding(.horizontal,8)
.onReceive(viewmodel.$scrollTop) { (scrollToTop) in
guard let first = articles.first,scrollToTop else { return}
reader.scrollTo(first,anchor: .top)
print(scrollToTop)
}
}
}
}
.background(Color.background.edgesIgnoringSafeArea(.all))
.navigationBarHidden(true)
.onAppear {
//viewmodel.getNews()
}
}
}
}
var articles: [Article] {
guard viewmodel.searchedArticles.isEmpty || viewmodel.searchText.count < 3 else { return viewmodel.searchedArticles}
return viewmodel.tabsArticles[viewmodel.selectedTab] ?? []
}
func checkActionForLastCell(index: Int) {
if index == articles.count - 1 {
viewmodel.getNextPageNews(isPaging: true)
}
}
}
在我的 viewmodel 中,我只是使用一个计时器来查看它是否收到通知
class NewsListviewmodel: ObservableObject {
/..../
@Published var scrollTop = false
init() {
dispatchQueue.main.asyncAfter(deadline: .Now() + 5) {
self.scrollTop = true
}
}
}
我打印了通知并且 reader.scrollTo(first,anchor: .top) 被执行...但我的表格没有滚动到顶部。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)