Just a coder
Just a coder

Reputation: 16690

What is the correct way to update ScrollView in SwiftUI? (MacOS App)

I am using officially released Xcode 11 from appstore. A number of things can be seen if you run the code below.

enter image description here

  1. Tapping on Root Press correctly adds the missing view#2, But there is no animation. Why is there no animation?
  2. Tapping any of the Press buttons, correctly adds a middle view, but if you look, you will see that the scrollView content size did not update and therefore the content is clipped. What is the correct way to update the 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() } }
        }
    }
}

Upvotes: 2

Views: 1062

Answers (1)

Rui Peres
Rui Peres

Reputation: 25907

Fixing the animations can be done via: .animation(.linear(duration: 0.3)). You can then remove all the animation blocks. (withAnimation { }). As for the bounds/frame, setting the frame helps (when adding the row at the root level), but it doesn't seem to work when you are dealing with an inner view. I added the following: .frame(width:UIScreen.main.bounds.width), and it will look like the following:

enter image description here

Upvotes: 6

Related Questions