0
0
iOS Swiftmobile~5 mins

Preference keys in iOS Swift

Choose your learning style9 modes available
Introduction

Preference keys help you share small pieces of information inside your app easily. They let different parts of your app talk to each other without being tightly connected.

When you want to pass simple data like sizes or colors from one view to another.
When you need to communicate layout information up the view tree.
When you want to keep your views independent but still share some settings.
When you want to collect values from multiple child views into a parent view.
When you want to avoid using global variables or complex data passing.
Syntax
iOS Swift
struct MyPreferenceKey: PreferenceKey {
    static var defaultValue: Int = 0
    static func reduce(value: inout Int, nextValue: () -> Int) {
        value += nextValue()
    }
}

The PreferenceKey protocol requires a defaultValue and a reduce function.

The reduce function combines multiple values from child views.

Examples
This key finds the maximum width from child views.
iOS Swift
struct MaxWidthKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = max(value, nextValue())
    }
}
This key passes a color preference from child to parent.
iOS Swift
struct ColorPreferenceKey: PreferenceKey {
    static var defaultValue: Color = .clear
    static func reduce(value: inout Color, nextValue: () -> Color) {
        value = nextValue()
    }
}
Sample App

This example measures the width of two text views and shows the maximum width below them. It uses a preference key to pass width values up the view tree.

iOS Swift
import SwiftUI

struct MaxWidthKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = max(value, nextValue())
    }
}

struct ContentView: View {
    @State private var maxWidth: CGFloat = 0

    var body: some View {
        VStack {
            Text("Short")
                .background(GeometryReader { geo in
                    Color.clear.preference(key: MaxWidthKey.self, value: geo.size.width)
                })
            Text("A much longer text")
                .background(GeometryReader { geo in
                    Color.clear.preference(key: MaxWidthKey.self, value: geo.size.width)
                })
            Text("Max width: \(maxWidth, specifier: "%.1f")")
                .padding()
        }
        .onPreferenceChange(MaxWidthKey.self) { value in
            maxWidth = value
        }
        .padding()
    }
}
OutputSuccess
Important Notes

Preference keys are great for passing data from child views to parent views.

Use GeometryReader with preference keys to measure view sizes.

The reduce method lets you combine multiple values, like finding a max or sum.

Summary

Preference keys let views share simple data up the view hierarchy.

They require a default value and a reduce function to combine values.

Commonly used with GeometryReader to pass layout info.