File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 引数を持つmodifierを提供する
2
+
3
+ 引数内で状態の条件分岐を記述できるよう、引数を持つmodifierを提供します。
4
+
5
+ ## Overview
6
+
7
+ SwiftUIでは、条件に応じてViewの見た目や振る舞いを変更することがよくあります。引数のないmodifierを使用する場合、利用側は` if ` 文による条件分岐を使用するしかありませんが、これはView identityが変更され、パフォーマンスの低下を招きます。
8
+
9
+ 引数を持つmodifierを提供することで、利用側はmodifierの引数の中で条件分岐を記述でき、View identityを保持したままmodifierを条件によって変更できます。
10
+
11
+ ### 引数のないmodifierの問題点
12
+
13
+ 引数のないmodifierを条件分岐によって切り替えるには、` if ` 文を使用する必要があります:
14
+
15
+ ``` swift
16
+ struct ContentView : View {
17
+ @State var condition = false
18
+
19
+ var body: some View {
20
+ if condition {
21
+ Text (" nice" )
22
+ .nicelyStyled ()
23
+ } else {
24
+ Text (" nice" )
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ この実装では、` condition ` の値が変わるたびに、` Text ` がView identityの異なるViewに再構築されます。これにより、状態変更のたびに完全な再構築が必要となり、パフォーマンスが低下します。
31
+
32
+ ### 条件分岐をmodifierの引数に移動する
33
+
34
+ 引数を持つmodifierを提供すると、条件分岐を引数に移動することで同一のView identityで表現できます:
35
+
36
+ ``` swift
37
+ struct ContentView : View {
38
+ @State var condition = false
39
+
40
+ var body: some View {
41
+ Text (" nice" )
42
+ .textStyle (condition ? .nicely : .primary )
43
+ }
44
+ }
45
+ ```
46
+
47
+ ## See Also
48
+ - < doc:WhatISViewIdentity >
Original file line number Diff line number Diff line change 45
45
46
46
### The Art of API Design
47
47
- < doc:ProvidesContainerViewAccessViaProxy >
48
+ - < doc:ProvideModifierWithParameter >
48
49
49
50
### Key priciples of the User Interface
50
51
- < doc:UserOwnsTheirInput >
You can’t perform that action at this time.
0 commit comments