@State 프로퍼티 래퍼를 정의한 구조체는 State 라고 부른다. 이것은 generic 구조체로 어떤 타입이든 받을 수 있다.
wrappedValue 와 projectedValue 프로퍼티들은 @State 값을 저장하기 위해 이 State 구조체에 의해 정의된 속성입니다. wrappedValue 프로퍼티는 state 프로퍼티에 값을 저장한 값 즉 프로퍼티 래퍼로 감싼 프로퍼티가 실제로 저장하는 값입니다.
struct PlayButton: View {
@State private var isPlaying: Bool = false
var body: some View {
Button(isPlaying ? "Pause" : "Play") {
isPlaying.toggle()
print(isPlaying.wrappedValue) // true
}
}
}
projectedValue 프로퍼티는 뷰 계층적으로 하위 계층에 binding value를 넘길 때 사용합니다. projectedValue 를 가져오기 위해서 '$' 를 사용합니다. 다음 예제에서는 PlayerView 는 state property인 isPlaying 을 PlayButton 뷰에 $isPlaying을 사용하여 보여줍니다.
struct PlayerView: View {
var episode: Episode
@State private var isPlaying: Bool = false
var body: some View {
VStack {
Text(episode.title)
.foregroundStyle(isPlaying ? .primary : .secondary)
PlayButton(isPlaying: $isPlaying)
}
}
}
import SwiftUI
struct ContentView: View {
@State private var title: String = "Default Title"
@State private var titleInput: String = ""
var body: some View {
VStack {
Text(_title.wrappedValue)
.padding(10)
TextField("Insert Title", text: _titleInput.projectedValue)
.textFieldStyle(.roundedBorder)
Button(action: {
_title.wrappedValue = _titleInput.wrappedValue
_titleInput.wrappedValue = ""
}, label: { Text("Change Title") })
Spacer()
}.padding()
}
}
#Preview {
ContentView()
}
'SwiftUI' 카테고리의 다른 글
Files and Directories - 파일 디렉터리 접근 (0) | 2023.11.11 |
---|---|
Button (0) | 2023.11.11 |
property wrapper (0) | 2023.11.10 |
Property, Method (0) | 2023.11.10 |
Environment (0) | 2023.11.08 |