Andrew_STOP_RU_WAR_IN_UA
Andrew_STOP_RU_WAR_IN_UA

Reputation: 11436

Correct way to get size of SwiftUI view and write it to Model

I have some model:

public struct someModel{
    var someContent: CGSize
}

I have someView:


struct StatusEntryView: View {
    @ObservedObject var model : someModel

    var body: some View {
        ScrollView([Axis.Set.horizontal, Axis.Set.vertical]) {
            GeometryReader { gr in
                VStack{
                    ForEach(self.model.hunks){ hunk in
                        HunkView(hunk: hunk)
                    }
                }

            self.model.contentSize = gr.size
            }
        }
    }
}

what is correct way to get ScrollView's actual content size and write it into model?

Upvotes: 1

Views: 189

Answers (1)

Asperi
Asperi

Reputation: 257663

It can be done with GeometryReader but not in that place, here it is

ScrollView([Axis.Set.horizontal, Axis.Set.vertical]) {
    VStack{
        ForEach(self.model.hunks){ hunk in
            HunkView(hunk: hunk)
        }
    }.background(GeometryReader { gr in
        self.model.contentSize = gr.size // might be needed wrap in async
        return Rectangle().fill(Color.clear)
    })
}

Note: pay attention on comment in code, cause now it is not clear how you're going to use that size, but if you'll right ahead from there change layout of views then it will be needed to wrap inDispatchQueue.main.async {}` to avoid view update cycling.

Upvotes: 1

Related Questions