🌱
environmentObject(_:)、environment(_:_:)、environment(_:) の違いと使い方
概要
-
environmentObject(_:)、environment(_:_:)、environment(_:)ので使い方などをまとめる
environmentObject(_:)
- 主な用途:
ObservableObjectでUI状態や設定情報をアプリ全体で共有したい時 - 事前準備:
ObservableObject準拠クラスを定義する - 提供側(親ビュー):
.environmentObject(store) - 利用側(子ビュー):
@EnvironmentObject private var store: StoreType
コード
import SwiftUI
import Combine
/// アプリ全体の通知バッジ数を管理するストア。
final class NotificationBadgeStore: ObservableObject {
/// 未読通知の件数。
@Published var unreadCount = 0
/// 未読数を 1 件増やす。
func increment() {
unreadCount += 1
}
/// 未読数をリセットする。
func reset() {
unreadCount = 0
}
}
struct RootScreen: View {
/// バッジ数ストア
@StateObject private var badgeStore = NotificationBadgeStore()
var body: some View {
TabView {
TimelineScreen()
.tabItem {
Label("Timeline", systemImage: "list.bullet")
}
SettingsScreen()
.tabItem {
Label("Settings", systemImage: "gearshape")
}
}
// アプリ全体にNotificationBadgeStoreを共有する
.environmentObject(badgeStore)
}
}
/// タイムライン画面
struct TimelineScreen: View {
/// バッジ数ストアを環境変数から取得
@EnvironmentObject private var badgeStore: NotificationBadgeStore
var body: some View {
NavigationStack {
VStack(spacing: 20) {
Text("Unread: \(badgeStore.unreadCount)")
Button("Add unread") {
badgeStore.increment()
}
Button("Reset") {
badgeStore.reset()
}
}
.navigationTitle("Timeline")
}
}
}
/// 設定画面(同じストアを共有)
struct SettingsScreen: View {
/// バッジ数ストアを環境変数から取得
@EnvironmentObject private var badgeStore: NotificationBadgeStore
var body: some View {
NavigationStack {
Text("Unread: \(badgeStore.unreadCount)")
.navigationTitle("Settings")
}
}
}
参考資料
environment(_:_:)
- 主な用途: Repository、UseCase、APIクライアント、設定値など、UIとは一段分離された依存オブジェクトの注入(DI)
- 事前準備:
-
EnvironmentValuesのextensionを定義する - struct、class、actorなど好きな型
-
EnvironmentKeyの実装、または@Entryマクロで定義する
-
- 提供側(親ビュー):
.environment(\.apiClient, apiClient) - 利用側(子ビュー):
@Environment(\.apiClient) private var apiClient: ApiClient
コード
import SwiftUI
// MARK: - AppStyle
/// スタイル設定。
struct AppStyle {
var primaryColor: Color
var secondaryColor: Color
}
// MARK: - EnvironmentKey 定義
///// `EnvironmentValues`に`AppStyle`を格納するためのキー。
//private struct AppStyleKey: EnvironmentKey {
// static var defaultValue: AppStyle = AppStyle(
// primaryColor: .blue,
// secondaryColor: .gray
// )
//}
//
//extension EnvironmentValues {
// var appStyle: AppStyle {
// get { self[AppStyleKey.self] }
// set { self[AppStyleKey.self] = newValue }
// }
//}
// MARK: EnvironmentKey 定義 (@Entryバージョン)
extension EnvironmentValues {
/// `EnvironmentValues` に登録される `AppStyle` のエントリ。
@Entry var appStyle: AppStyle = AppStyle(
primaryColor: .blue,
secondaryColor: .gray
)
}
// MARK: - 提供側(親ビュー)
struct StyleRootView: View {
/// 実際に使うスタイル設定
private let appStyle = AppStyle(
primaryColor: .orange,
secondaryColor: .brown
)
var body: some View {
StyledContentView()
.environment(\.appStyle, appStyle)
}
}
// MARK: - 利用側(子ビュー)
struct StyledContentView: View {
/// 環境からスタイルを取得
@Environment(\.appStyle) private var appStyle
var body: some View {
VStack(spacing: 16) {
Text("Primary")
.padding()
.frame(maxWidth: .infinity)
.background(appStyle.primaryColor)
.foregroundStyle(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
Text("Secondary")
.padding()
.frame(maxWidth: .infinity)
.background(appStyle.secondaryColor)
.foregroundStyle(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
}
.padding()
}
}
参考資料
environment(_:)
- 主な用途:
ObservationでUI状態や設定情報をアプリ全体で共有したい時 - 事前準備:
@Observable準拠クラスを定義する - 提供側(親ビュー):
.environment(store)(型をキーとして注入) - 利用側(子ビュー):
@Environment(StoreType.self) private var store- Bindingが必要ならbody内で
@Bindable var store = storeとする
コード
import SwiftUI
import Observation
/// アプリ全体の通知バッジ数を管理するストア。
@Observable class NotificationBadgeStore {
/// 未読通知の件数。
var unreadCount = 0
/// 未読数を 1 件増やす。
func increment() {
unreadCount += 1
}
/// 未読数をリセットする。
func reset() {
unreadCount = 0
}
}
struct RootScreen: View {
/// バッジ数ストア
@State private var badgeStore = NotificationBadgeStore()
var body: some View {
TabView {
TimelineScreen()
.tabItem {
Label("Timeline", systemImage: "list.bullet")
}
SettingsScreen()
.tabItem {
Label("Settings", systemImage: "gearshape")
}
}
// アプリ全体にNotificationBadgeStoreを共有する
.environment(badgeStore)
}
}
/// タイムライン画面
struct TimelineScreen: View {
/// バッジ数ストアを環境変数から取得
@Environment(NotificationBadgeStore.self) private var badgeStore: NotificationBadgeStore
var body: some View {
NavigationStack {
VStack(spacing: 20) {
Text("Unread: \(badgeStore.unreadCount)")
Button("Add unread") {
badgeStore.increment()
}
Button("Reset") {
badgeStore.reset()
}
}
.navigationTitle("Timeline")
}
}
}
/// 設定画面(同じストアを共有)
struct SettingsScreen: View {
/// バッジ数ストアを環境変数から取得
@Environment(NotificationBadgeStore.self) private var badgeStore: NotificationBadgeStore
var body: some View {
NavigationStack {
Text("Unread: \(badgeStore.unreadCount)")
.navigationTitle("Settings")
}
}
}
参考資料
参考資料
Discussion