Nuevas envolturas de propiedades en SwiftUI

¡Hola, Khabrovites! A finales de agosto, un nuevo grupo del curso básico profesional "Desarrollador iOS" comenzará en OTUS . Como siempre, compartimos una traducción útil y lo invitamos a eventos en línea gratuitos: "Open Day" y "Quick Start to IOS Development" .








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