Nouveaux emballages de propriétés dans SwiftUI

Bonjour, Khabrovites! Fin août, un nouveau groupe du cours de base professionnel "Développeur iOS" débutera à OTUS . Comme toujours, nous partageons une traduction utile et vous invitons à des événements en ligne gratuits: «Journée portes ouvertes» et «Démarrage rapide du développement IOS» .








WWDC20 SwiftUI , . SwiftUI (Property Wrappers) @StateObject, @AppStorage, @SceneStorage @ScaledMetric.



, SwiftUI, « Property Wrappers SwiftUI».


StateObject



, SwiftUI @ObservedObject, , SwiftUI. , , - . @ObservedObject . - SwiftUI, , , SceneDelegate AppDelegate. , @ObservedObject.



StateObject SwiftUI. SwiftUI StateObject , . StateObject State, .



struct CalendarContainerView: View {
    @StateObject var viewModel = ViewModel()

    var body: some View {
        CalendarView(viewModel.dates)
            .onAppear(perform: viewModel.fetch)
    }
}


AppStorage



AppStorage , . - UserDefaults. AppStorageDynamicProperty, , SwiftUI , UserDefaults. AppStorage . , .



enum Settings {
    static let notifications = "notifications"
    static let sleepGoal = "sleepGoal"
}

struct SettingsView: View {
    @AppStorage(Settings.notifications) var notifications: Bool = false
    @AppStorage(Settings.sleepGoal) var sleepGoal: Double = 8.0

    var body: some View {
        Form {
            Section {
                Toggle("Notifications", isOn: $notifications)
            }

            Section {
                Stepper(value: $sleepGoal, in: 6...12) {
                    Text("Sleep goal is \(sleepGoal, specifier: "%.f") hr")
                }
            }
        }
    }
}


, AppStorage Form. AppStorage, - , SwiftUI .



struct ContentView: View {
    @AppStorage(Settings.sleepGoal) var sleepGoal = 8
    @StateObject var store = SleepStore()

    var body: some View {
        WeeklySleepChart(store.sleeps, goal: sleepGoal)
            .onAppear(perform: store.fetch)
    }
}


SceneStorage



SwiftUI UIKit. SceneStorage, . SceneStorage AppStorage, UserDefaults . , , . , SceneStorage.



struct ContentView: View {
    @SceneStorage("selectedTab") var selection = 0

    var body: some View {
        TabView(selection: $selection) {
            Text("Tab 1").tag(0)
            Text("Tab 2").tag(1)
        }
    }
}


SceneStorage , , . iOS , .



ScaledMetric



ScaledMetric. ScaledMetric Dynamic Type. , Dynamic Type. .



struct ContentView: View {
    @ScaledMetric(relativeTo: .body) var spacing: CGFloat = 8

    var body: some View {
        VStack(spacing: spacing) {
            ForEach(0...10, id: \.self) { number in
                Text(String(number))
            }
        }
    }
}


Dynamic Type, SwiftUI .





SwiftUI. , , , . Twitter , . !






« iOS»







All Articles