Skip to content

Commit c5dfda5

Browse files
authored
Merge pull request #3 from cybozu/provide-modifier-with-parameter
引数を持つmodifierを提供する
2 parents c448e9d + c9d9d8e commit c5dfda5

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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>

Guide.docc/SwiftUIViewCodingGuidelines.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545

4646
### The Art of API Design
4747
- <doc:ProvidesContainerViewAccessViaProxy>
48+
- <doc:ProvideModifierWithParameter>
4849

4950
### Key priciples of the User Interface
5051
- <doc:UserOwnsTheirInput>

0 commit comments

Comments
 (0)