问题描述
向我的 ListView 添加内容时,我希望它自动向下滚动.
When adding content to my ListView, I want it to automatically scroll down.
我使用 SwiftUI List
和 BindableObject
作为控制器.新数据正在添加到列表中.
I'm using a SwiftUI List
, and a BindableObject
as Controller. New data is getting appended to the list.
List(chatController.messages, id: .self) { message in
MessageView(message.text, message.isMe)
}
我希望列表向下滚动,因为我将新数据附加到消息列表中.但是我必须手动向下滚动.
I want the list to scroll down, as I append new data to the message list. However I have to scroll down manually.
推荐答案
更新:在 iOS 14 中,现在有一种原生方式可以做到这一点.我就是这样做的
Update: In iOS 14 there is now a native way to do this.I am doing it as such
ScrollViewReader { scrollView in
ScrollView(.vertical) {
LazyVStack {
ForEach(notes, id: .self) { note in
MessageView(note: note)
}
}
.onAppear {
scrollView.scrollTo(notes[notes.endIndex - 1])
}
}
}
对于 iOS 13 及更低版本,您可以尝试:
For iOS 13 and below you can try:
我发现翻转视图对我来说似乎很有效.这会在底部启动 ScrollView,并且在向其添加新数据时会自动向下滚动视图.
I found that flipping the views seemed to work quite nicely for me. This starts the ScrollView at the bottom and when adding new data to it automatically scrolls the view down.
- 将最外面的视图旋转 180
.rotationEffect(.radians(.pi))
- 在垂直平面上翻转它
.scaleEffect(x: -1, y: 1, anchor: .center)
您也必须对内部视图执行此操作,因为现在它们都将被旋转和翻转.要将它们翻转回来,请执行上述相同的操作.
You will have to do this to your inner views as well, as now they will all be rotated and flipped. To flip them back do the same thing above.
如果您需要这么多地方,可能值得为此自定义视图.
If you need this many places it might be worth having a custom view for this.
您可以尝试以下操作:
List(chatController.messages, id: .self) { message in
MessageView(message.text, message.isMe)
.rotationEffect(.radians(.pi))
.scaleEffect(x: -1, y: 1, anchor: .center)
}
.rotationEffect(.radians(.pi))
.scaleEffect(x: -1, y: 1, anchor: .center)
这是一个用于翻转它的视图扩展
Here's a View extension to flip it
extension View {
public func flip() -> some View {
return self
.rotationEffect(.radians(.pi))
.scaleEffect(x: -1, y: 1, anchor: .center)
}
}
这篇关于如何使 SwiftUI 列表自动滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!