본문 바로가기
Language/Swift

SwiftUI 에서 데이터 다루기 (@State, @ObservedObject)

by IFLA 2023. 1. 5.

사용자가 버튼을 누르거나 스크롤을 하거나 특정행동을 하면 State 즉 상태가 변경된다. 이후에 State 가 변경되면 자동으로 변환시켜주는 일을 한다. 사용자 인터페이스를 업데이트를 한다.

상태를 변경할 때마다 body 속성이 재설정된다. 뷰 자체가 다시 랜더링된다. 즉 State 를 변경할 때마다 항상 새로운 View 에서 랜더링 된다.

@State 는 struct 를 필수적으로 사용해야 한다.

 

@State

기본 코드

struct User {
	var firstName = ""
	var lastName = ""
}

struct ContentView: View {
	var body: some View {
		VStack {
			Text("당신의 이름은 \\(user.fristName)\\(user.lastName) 입니다")
          .font(.title)
          .fontWeight(.bold)
          .padding(30)
      
      List {
          Section(header: Text("이름을 입력하세요").font(.headline)) {
          
              TextField("성", text: $user.fristName)
              TextField("이름", text: $user.lastName)
          }
      }
		}
	}
}

 

실행 화면


 

@ObservedObject

  • 복잡한 프로퍼티(여러 프로퍼티나 메서드가 있거나, 여러 view 에서 공유할 수 있는 커스텀 타입이 있는 경우 사용)

기본 코드

class UserSettings: ObservableObject {
	@Published var score = 0
}

struct ContentView: View {
	@ObservedObject var settings = UserSettings()

	var body: some View {
		VStack {
			Text("나의 점수는 \\(settings.score)점 입니다.")
			Button(action: {
				self.settings.score += 1
			}) {
				Text("Increase Score")
			}
		}	
	}
}

score 에 @Published 가 붙었기 때문에 score 가 변경되면 view를 reload를 하게 된다.

 

실행 화면

 


개발자 Document

Apple Developer Documentation

 

Apple Developer Documentation

 

developer.apple.com

https://developer.apple.com/documentation/swiftui/observedobject

 

Apple Developer Documentation

 

developer.apple.com

 

댓글


\