import SwiftUI
struct ContentView: View {
@State private var isPlaying: Bool = true
var body: some View {
Button(isPlaying ? "Play" : "Pause") {
isPlaying.toggle()
}
}
}
struct PlayerView: View {
var movie: Movie
@State private var isPlaying: Bool = false
var body: some View {
VStack {
Text(movie.title)
.foregroundStyle(isPlaying ? .primary : .secondary)
PlayButton(isPlaying: $isPlaying)
}
}
}
struct PlayButton: View {
@Binding var isPlaying: Bool
var body: some View {
Button(isPlaying ? "Pause" : "Play") {
isPlaying.toggle()
}
}
}
class Contact: ObservedObject {
@Published var name: String
@Published var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func haveBirthday() -> Int {
age += 1
return age
}
}
let han = Contact(name: "Han", age: 20)
cancellable = han.objectWillChange
.sink { _ in
print(han.age)
}
print(han.haveBirthday())
class User: ObservableObject {
@Published var age = 20
}
struct ContentView: View {
@ObservedObject var user: User
var body: some View {
Button("Get Age") {
user.age += 1
}
}
}
@ObjervedObject는 상태 변경이 있을 때 뷰를 다시 생성해서 그리지만, @StateObject는 뷰를 다시 생성하지 않고 항상 동일한 뷰를 사용(효율)
※ Tip
기본적으로 @StateObject를 사용하되, 해당 프로퍼티를 subview에게도 주입시켜야 한다면, @ObservedObject를 사용하는 것이 좋다.
struct ContentView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
Text("Hello, World!!!")
.foregroundStyle(colorScheme == .dark ? .white : .black)
}
}
남발하면 데이터 의존성에 문제가 발생(코드 유지 보수 어렵고 버그 유발)
데이터의 일관성을 유지하기 힘들다.(데이터 관리의 복잡도 증가)
@EnvironmentObject에 의존하면 단위 테스트, UITest 작성하기 어려워진다.
class Info: ObservableObject {
@Published var num = 20
}
@main
struct SwiftUI_TestApp: App {
var body: some Scene {
WindowGroup {
MainView()
.environmentObject(Info())
}
}
}
struct MainView: View {
@EnvironmentObject var info: Info
var body: some View {
Button(action: {
self.info.num += 1
}, label: {
Text("Plus Number")
})
SubView()
}
}
struct SubView: View {
@EnvironmentObject var info: Info
var body: some View {
Button(action: {
self.info.num -= 1
}, label: {
Text("Minus Number")
})
}
}