[SwiftUI] Managing user interface state
2025. 1. 27. 22:03
struct PlayerView: View{
@State private var isPlaying: Bool = false
var body: some View{
PlayButton(isPlaying: $isPlaying)
}
}
struct PlayButton: View{
@Binding var isPlaying: Bool
var body: some View{
Button(action:{
self.isPlaying.toggle()
}){
Image(systemName:isPlaying ? "pause.circle" : "play.circle")
}
}
}
사용자 인터페이스(UI) 상태 관리
앱의 View 계층 구조 내의 View 별 데이터를 캡슐화 하여 View를 재사용할 수 있도록 합니다.
SwiftUI에서는 값을 수정하려면 Swift에서 처럼 body 내에서 값을 변경 할 수 없습니다.
SwiftUI에서 데이터는 View의 최소 공통 조상에 상태로 저장되고 단일 진실의 출처를 제공합니다.
이를 통해 데이터는 뷰 간에 공유되고, SwiftUI는 데이터 변화를 감시하여 필요한 경우 영향을 받는 뷰를 자동으로 업데이트 합니다.
상태 관리
상태를 관리하기 위해 @State 를 사용하여 뷰 내에서 수정 가능한 값을 선언합니다.
코드에서는 PlayerView의 재생상태를 관리할 수 있습니다.
struct PlayerView: View {
@State private var isPlaying: Bool = false // 플레이어 재생 상태
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
불변 값 저장
View가 수정하지 않는 데이터를 제공하려면 표준 Swift의 속성을 사용합니다.
코드에서는 에피소드 정보를 저장할 수 있습니다.
struct PlayerView: View {
let episode: Episode // 에피소드 정보
@State private var isPlaying: Bool = false
var body: some View {
Text(episode.title)
// ...
}
}
바인딩으로 상태 공유
자식 뷰와 상태를 공유하고자 할 때 @Binding을 사용합니다. Binding은 기존 저장소에 대한 참조를 제공하여 양방향 연결을 유지합니다.
코드에서 먼저 플레이 버튼에서 플레이어 재생상태 isPlaying를 선언합니다.
struct PlayButton: View {
@Binding var isPlaying: Bool
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
부모 뷰에서 바인딩을 전달하는 방법입니다.
struct PlayerView: View {
@State private var isPlaying: Bool = false
var body: some View {
PlayButton(isPlaying: $isPlaying) // 플레이 버튼 선언
}
}
애니메이션 적용
상태 변화에 애니메이션을 적용하려면 withAnimation 함수를 사용합니다.
withAnimation {
self.isPlaying.toggle()
}
scale를 추가하여 애니메이션을 구현할 수 있습니다.
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
.scaleEffect(isPlaying ? 1 : 1.5)
728x90
'iOS > SwiftUI' 카테고리의 다른 글
[SwiftUI] GeometryReader (2) | 2024.10.13 |
---|---|
[SwiftUI] List (2) | 2024.10.05 |
[SwiftUI] Button (0) | 2024.04.21 |
[SwiftUI] 공식문서 파헤치기 (3) [Spacer / Divider] (0) | 2023.08.12 |
[SwiftUI] 공식문서 파헤치기 (2) [Stack] (0) | 2023.08.12 |