정의
Swift 자체에서 특정한 기능이나 패턴들을 재사용하기 위해서 속성 즉 프로퍼티에 적용할 수 있는 사용자 정의 속성, modifier
struct PlayButton:View{
@State private var isPlaying:Bool = false
var body: some View{
Button(isPlaying?"Pause":"Play"){
isPlaying.toggle()
}
}
}
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) //binding
}
}
}
struct PlayButton:View{
@Binding var isPlaying:Bool = false
var body: some View{
Button(isPlaying?"Pause":"Play"){
isPlaying.toggle()
}
}
}
class Contact: ObservableObject{
@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 john = Contact(name:"John", age:24)
cancellable = john.objectWillChange
.sink{ _ in
print("\(join.age) will change")
}
print(john.haveBirthday())
class User: ObservableObject{
@Published var age = 10
}
struct ContentView: View{
@ObservedObject var user: User
var body: some View{
Button("Plus age"){
user.age += 1
}
}
}
struct ContentView: View{
@Environment(\.colorScheme) var colorScheme
var body: some View{
Text("Hello World")
.foregroundColor(colorScheme == .dark ? .white : .black)
}
}
class Info: ObservableObject{
@Published var age = 10
}
@main
struct MyApp: App{
var body: some Scene{
WindowGroup{
MainView()
.environmentObject(Info())
}
}
}
struct MainView: View{
@EnvironmentObject var info: Info
var body: some View{
Button(action: {
self.info.age += 1
}) {
Text("Click Me for plus age")
}
SubView()
}
}
struct SubView: View{
@EnvironmentObject var info: Info
var body: some View{
Button(action: {
self.info.age -= 1
}) {
Text("Click Me for minus age")
}
}
}