PreferenceKey
Collect info from children views.
PreferenceKey
Collect info from children views.
0
0
Checkbox to mark video as read
Mark as read

Introduction

In SwiftUI, data generally flows downwards, meaning data is passed from parent views to child views. However, there are situations where you may want to pass data in the opposite direction—from a child view to a parent view. SwiftUI’s PreferenceKey protocol is a powerful solution for these cases. PreferenceKey enables data to travel up the view hierarchy, allowing parent views to access values defined in their child views.

Creating a Custom PreferenceKey

To create a PreferenceKey, start by defining a new struct that conforms to the PreferenceKey protocol. This struct must have a defaultValue and a reduce function to aggregate multiple values.

struct MyPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 0

    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value += nextValue()
    }
}

Continue reading

Access to all the content with our plans.

Basic Plan

FREE

Start Now
  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions
Monthly
Yearly

Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy