如何使SwiftUI列表自动滚动? [英] How to make a SwiftUI List scroll automatically?

查看:541
本文介绍了如何使SwiftUI列表自动滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将内容添加到ListView时,我希望它自动向下滚动.

When adding content to my ListView, I want it to automatically scroll down.

我正在使用SwiftUI列表"和"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.

推荐答案

我发现翻转视图对我来说似乎很好.这将在底部启动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.

  1. 旋转最外面的视图180 .rotationEffect(.radians(.pi))
  2. 将其翻转到垂直平面.scaleEffect(x: -1, y: 1, anchor: .center)
  1. Rotate the outermost view 180 .rotationEffect(.radians(.pi))
  2. Flip it across the vertical plane .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)

这是一个可以将其翻转的View扩展

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列表自动滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆