Created
January 23, 2020 02:24
-
-
Save yimajo/6d47b406fe0161ac68c46cd7321f4b38 to your computer and use it in GitHub Desktop.
SwiftUIのEnvironmentValuesはSubViewに伝搬するしカスタムなKeyも指定できる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*: | |
# EnvironmentValuesはSubViewに伝搬するしカスタムなKeyも指定できる | |
- EnvironmentValuesは特定のKeyに対して値を設定できる | |
- 標準のKey | |
- https://developer.apple.com/documentation/swiftui/environmentvalues | |
- EnvironmentValuesが特定のViewの項目にそのまま紐付いている | |
- 例えば標準のKeyである\.fontはView上のTextのfontと結びついている | |
- Keyの値がView暗黙的にバインディングされている感じ | |
- Viewで明示した場合はEnvironmentValuesは使われない | |
- 環境変数は上書きされる | |
- SubViewは親ViewのKeyの値をそのまま反映される | |
- EnvironmentValuesで設定したい値は変数として取得できる | |
- `@Environment(\.key) private var 変数名` | |
- EnvironmentValuesを@Environmentで取得しても書き込みはできない | |
- EnvironmentValuesは任意のKeyでプロパティを増やすことができる | |
- KeyはEnvironmentKeyに準拠 | |
*/ | |
import PlaygroundSupport | |
import SwiftUI | |
struct ContentView1: View { | |
var body: some View { | |
VStack { | |
// 環境変数が使われない例 | |
// このfontはEnvironmentValuesを使われない | |
Text("LargeTitle").font(.largeTitle) | |
// 環境変数が使われる例 | |
// このfontがEnvironmentValuesを使われる | |
Text("ContentView") | |
// 明示せずともSubViewに環境変数が使われる例 | |
SubView1() | |
// カスタムな環境変数を利用する例 | |
SubView2() | |
} | |
} | |
} | |
struct SubView1: View { | |
var body: some View { | |
VStack { | |
// このfontもEnvironmentValuesを使われる | |
Text("SubView1:") | |
} | |
.background(Color.blue) | |
} | |
} | |
struct SubView2: View { | |
// 指定されているEnvironmentValuesを変数に渡せる | |
// カスタムで追加したKeyのbaseColor | |
@Environment(\.baseColor) private var baseColor | |
var body: some View { | |
// Environmentは書き込みできない | |
// baseColor = .black | |
return VStack { | |
// このfontもEnvironmentValuesを使われる | |
Text("SubView2:") | |
.foregroundColor(baseColor) | |
} | |
.background(Color.purple) | |
} | |
} | |
// MARK: - | |
// 追加したいKeyをまず定義する | |
struct BaseColorKey: EnvironmentKey { | |
// デフォルト値が指定できる | |
static let defaultValue: Color = .white | |
} | |
extension EnvironmentValues { | |
// プロパティを増やしてKeyを使って保持できるようにする | |
var baseColor: Color { | |
get { self[BaseColorKey.self] } | |
set { self[BaseColorKey.self] = newValue } | |
} | |
} | |
// MARK: - | |
let contentView = ContentView1() | |
.environment(\.font, Font.system(size: 20).italic()) // 標準のKeyに値を指定 | |
.environment(\.baseColor, .yellow) // カスタムKeyに値を指定 | |
PlaygroundPage.current.liveView = UIHostingController(rootView: contentView) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment