: A property wrapper type that can read and write a value managed by SwiftUI
SwiftUI manages the storage of a property that you declare as state. When the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value. Use state as the single source of truth for a given value stored in a view hierarchy.
A State instance isn’t the value itself; it’s a means of reading and writing the value. To access a state’s underlying value, refer to it by its property name, which returns the wrappedValue property value. For example, you can read and update the isPlaying state property in a PlayButton view by referring to the property directly:
import SwiftUI
struct ContentView: View {
// MARK: - PROPERTIES
@State private var isPlaying: Bool = false
func playingStat() -> String {
return isPlaying ? "play" : "pause"
}
// MARK: - BODY
var body: some View {
VStack {
Image("swiftUI")
.resizable()
.scaledToFit()
.frame(width: 120, height: 120, alignment: .center)
Text("SwiftUI - Apple")
.fontWeight(.bold)
Spacer()
HStack {
Image(systemName: "shuffle")
Spacer()
Image(systemName: "backward.fill")
Spacer()
Button (action: {
isPlaying = !isPlaying
}) {
Image(systemName: "\(playingStat()).fill")
}
.colorMultiply(.black)
Spacer()
Image(systemName: "forward.fill")
Spacer()
Image(systemName: "repeat")
}
.frame(width: 200)
}
.frame(height: 180)
}
}
@State는 값 자체가 아닌 값을 읽고 쓰는 수단입니다.
You can get a binding to a state value by accessing the state’s projectedValue, which you get by prefixing the property name with a dollar sign ($)
$가 붙게 되면 프로퍼티 래퍼 자체를 받기 때문에, WrapperValue 값을 변경할 수 있습니다.
import SwiftUI
struct ContentView: View {
// MARK: - PROPERTIES
@State private var isPlaying: Bool = false
// MARK: - BODY
var body: some View {
VStack {
Image("swiftUI")
.resizable()
.scaledToFit()
.frame(width: 120, height: 120, alignment: .center)
Text("SwiftUI - Apple")
.fontWeight(.bold)
Spacer()
HStack {
Image(systemName: "shuffle")
Spacer()
Image(systemName: "backward.fill")
Spacer()
PlayButton(isPlaying: $isPlaying)
.colorMultiply(.black)
Spacer()
Image(systemName: "forward.fill")
Spacer()
Image(systemName: "repeat")
}
.frame(width: 200)
}
.frame(height: 180)
}
}
struct PlayButton: View {
@Binding var isPlaying: Bool
func playingStat() -> String {
return isPlaying ? "play" : "pause"
}
var body: some View {
Button (action: {
isPlaying = !isPlaying
}) {
Image(systemName: "\(playingStat()).fill")
}
}
}
결과물은 위와 동일합니다.
@Binding은 부모, 자식으로 관계를 짓는다면, 주가 되는 부모 뷰에서 한 번 선언을 해주고 다른 뷰들에서 사용을 위해서 사용하게 됩니다.
자식이 되는 뷰에서 선언을 하여 사용을 할 수 있으며, $를 앞에 붙여서 값을 변경할 수 있도록 합니다.
'Language > Swift' 카테고리의 다른 글
[SwiftUI] NavigationView (0) | 2022.09.12 |
---|---|
[SwiftUI] @Environment (0) | 2022.09.12 |
[Swift] xcode template file modified, Add Snippet (0) | 2022.09.10 |
[SwiftUI] @appstorage (0) | 2022.09.08 |
[SwiftUI] preview가 뭔데요? (0) | 2022.09.08 |
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!