Wednesday, February 8, 2023
HomeiOS Developmentios - SwiftUI PreferenceKey not Updating

ios – SwiftUI PreferenceKey not Updating

I am struggling making an attempt to implement a PreferenceKey. I’ve learn numerous articles, so
clearly I am lacking one thing. onPreferenceChange stories as soon as at simulator startup however
not throughout scrolling. Scrolling updates the textual content within the TextEditor overlay, however the
offsetCGSize property is outwardly by no means up to date. Here is a simplified model
of the code:

struct SOView: View {

    @State personal var firstText: String = "first"
    @State personal var secondText: String = "second"
    @State personal var thirdText: String = "third"

    @State personal var offsetCGSize: CGSize = .zero

    var physique: some View {
        ScrollView {
            VStack {
                ForEach(0..<20) {index in
                    Textual content("Line quantity (index)")
                Picture(systemName: "globe")
                TextField("First", textual content: $firstText)
                GeometryReader { teGeo in
                    TextEditor(textual content: $secondText)
                        .body(peak: 100)
                            RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2)
                            Textual content("(teGeo.body(in: .world).minY)")
                        .desire(key: OffsetPreferenceKey.self, worth: CGSize(width: 0, peak: teGeo.body(in: .world).minY))
                .body(peak: 100)
                TextField("Third", textual content: $thirdText)
                Textual content("TextEditor prime is (offsetCGSize.peak)")
        .onPreferenceChange(OffsetPreferenceKey.self) { worth in
            offsetCGSize = worth
            print("offsetCGSize is (offsetCGSize)")

}//so view

personal struct OffsetPreferenceKey: PreferenceKey {
    static var defaultValue: CGSize =
    static func cut back(worth: inout CGSize, nextValue: () -> CGSize) {
        worth = nextValue()
}//off pref

Any steerage can be appreciated. Xcode 14.0.1, iOS 16



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments