在 SwiftUI 中更新 ScrollView 的正确方法是什么?(MacOS 应用程序)

iOS*_*com 2 swift swiftui

我正在使用从 appstore 正式发布的 Xcode 11。如果您运行下面的代码,可以看到很多东西。

在此处输入图片说明

  1. 点击Root Press正确添加缺少的视图#2,但没有动画。为什么没有动画?
  2. 点击任何Press按钮,正确添加一个中间视图,但如果你看,你会看到 scrollView 内容大小没有更新,因此内容被裁剪。更新 ScrollView 的正确方法是什么?
import SwiftUI
struct ContentView: View {
    @State var isPressed = false
    var body: some View {
        VStack {
            Button("Root Press") { withAnimation { self.isPressed.toggle() } }
            ScrollView {
                Group {
                    SampleView(index: 1)
                    if isPressed { SampleView(index: 2) }
                    SampleView(index: 3)
                    SampleView(index: 4)
                }
                .border(Color.red)
            }
        }
    }
}

struct SampleView: View {
    @State var index: Int
    @State var isPressed = false
    var body: some View {
        HStack {
            VStack {
                Text("********************")
                Text("This View = \(index)")
                Text("********************")

                if isPressed {
                    Text("********************")
                    Text("-----> = \(index)")
                    Text("********************")
                }
            }
            Button("Press") { withAnimation { self.isPressed.toggle() } }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rui*_*res 5

修复动画可以通过:.animation(.linear(duration: 0.3))。然后您可以移除所有动画块。( withAnimation { }). 至于边界/框架,设置框架有帮助(在根级别添加行时),但在处理内部视图时似乎不起作用。我添加了以下内容:.frame(width:UIScreen.main.bounds.width),它将如下所示:

在此处输入图片说明