【问题标题】:Unable to scroll to the bottom of the list implemented with ScrollViewReader in SwiftUI无法滚动到在 SwiftUI 中使用 ScrollViewReader 实现的列表底部
【发布时间】:2022-01-22 23:34:45
【问题描述】:

我正在开发一个聊天应用程序,我需要根据消息交换的日期对消息进行分类。

View 的主体如下所示。

@ViewBuilder
private var bodyView: some View {
    ScrollView(.vertical) {
        ScrollViewReader { scrollView in

            LazyVStack {
                ForEach(chatItems, id: \.self) { chatItem in
                    Section(header: Label(chatItem.dateString, font: someFont))
                    {
                        ForEach(chatItem.msgItems) { msgItem in
                            ChatView(data: msgItem)
                        }
                    }
                }
            }
            .onAppear {
               
                if !chatItems.isEmpty {
                    scrollView.scrollTo(chatItems[chatItems.endIndex - 1],
                                        anchor: .bottom)
                }
            }
        }
    }.background(color: someColor)
}

从代码 sn-p 可以清楚地看出我有显示日期的部分,在这些部分中我显示属于该日期的消息。

我的问题: 上面的代码完美运行我能够很好地渲染视图,并且它也滚动到最后一部分。我无法实现的是,我希望滚动视图滚动到属于最后一部分的结束消息。但目前它停在该部分,它不会在下面。

我尝试过的。

我尝试将此添加到内部 forEach 中的“.onAppear”中。

 .onAppear {
        
        scrollView.scrollTo(chatItem.msgItems[chatItem.msgItems.endIndex - 1], anchor: .bottom)
    }
    

它什么也没做。

我还尝试强制滚动到外部“.onAppear”中最后一个部分的最后一个消息,它没有做任何事情,它甚至不会滚动到最后一个部分,通常使用上面的代码。

如果帮助解决问题,如果我的问题不清楚,我愿意编辑或进一步解释。

【问题讨论】:

  • 跟进 Asperi 评论:这是有效的。 ForEach(groupItem.chatItem, id: .\self) { chatItem....} 我错过了将 id 放入 forEach 所以 scrollView 无法滚动到该对象

标签: swiftui swiftui-list


【解决方案1】:

scrollTo.id 工作,因此您必须明确指定每个视图的标识符,例如(假设 msgItem 符合此需求,否则使用您的逻辑的相应 id):

ForEach(chatItem.msgItems) { msgItem in
    ChatView(data: msgItem).id(msgItem)     // << here !!
}

查看示例和详细信息https://stackoverflow.com/a/60855853/12299030

【讨论】:

  • 感谢您的指出。我接受了这个答案,但是我正在添加有效的更改(您的建议)
猜你喜欢
  • 2020-01-19
  • 1970-01-01
  • 2022-10-17
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2021-01-10
  • 2020-02-11
相关资源
最近更新 更多