위 글은 유튜브 정대리님의 SwiftUI fundamental Tutorial 강좌를 보고 작성한 정리글로
자세한 내용은 유튜브를 통해 확인하시길 권장합니다.
바인딩(Binding) = 묻는다
데이터의 상태를 묻고 뷰와 뷰끼리의 데이터 공유가 가능해짐
MyStackView에서 데이터 연동하기
import SwiftUI
struct MyStackView: View{
@Binding
var isActivated: Bool //외부에서 접근해야하므로 private 안씀
init(isActivated: Binding<Bool> = .constant(false)){
_isActivated = isActivated
}
var body: some View{
VStack{
Text("1!")
.fontWeight(.bold)
.font(.system(size: 50))
Text("2!")
.fontWeight(.bold)
.font(.system(size: 50))
Text("3!")
.fontWeight(.bold)
.font(.system(size: 50))
}
.background(self.isActivated ? Color.green : Color.red)
.padding(self.isActivated ? 10 : 0)
}
}
@Binding: 데이터를 연동시키기 위함
바인딩을 사용하기 위해선 생성자를 사용해줘야 함
init(isActivated: Binding<Bool> = .constant(false)){
_isActivated = isActivated
}
MyStackView()에 데이터를 넘겨서 연결시켜 줌: MyStackView(isActivated: $isActivated)
import SwiftUI
struct ContentView: View {
//@State: 값의 변화를 감지하여 뷰에 적용
@State
private var isActivated: Bool = false
var body: some View {
NavigationView{
VStack{
HStack{
MyStackView(isActivated: $isActivated)
MyStackView(isActivated: $isActivated)
MyStackView(isActivated: $isActivated)
}
.background(isActivated ? Color.yellow : Color.black)
.onTapGesture {
print("HStack 클릭됨")
withAnimation{
self.isActivated.toggle()
}
}
NavigationLink(destination: MyTextView(isActivated: $isActivated)){
Text("네비게이션")
.font(.system(size: 40))
.fontWeight(.bold)
.padding()
.background(Color.yellow)
.foregroundColor(Color.white)
.cornerRadius(30)
}
.padding(.top, 50)
}
}
}
}
네비게이션 뷰에서 바인딩하기
import SwiftUI
struct MyTextView: View{
@Binding
var isActivated: Bool
init(isActivated: Binding<Bool> = .constant(false)){
_isActivated = isActivated
}
@State
private var index: Int = 0
private let backgroundColors = [
Color.red,
Color.yellow,
Color.green,
Color.blue,
Color.purple
]
var body: some View{
VStack{
Spacer()
Text("배경 아이템 인덱스 \(self.index)")
.font(.system(size: 30))
.fontWeight(.bold)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 100)
Text("활성화 상태: \(String(isActivated))")
.font(.system(size: 30))
.fontWeight(.bold)
.foregroundColor(self.isActivated ? Color.yellow : Color.gray)
.background(Color.black)
Spacer()
}.background(backgroundColors[index])
.edgesIgnoringSafeArea(.all)
.onTapGesture {
print("배경 아이템이 클릭 되었습니다")
if(self.index == self.backgroundColors.count - 1){
self.index = 0
}
else{
self.index += 1
}
}
}
}
SwiftUI에서 Bool 타입을 텍스트로 사용하기 위해서 String으로 감싸주면 됨: \(String(isActivated))
'강의 > etc' 카테고리의 다른 글
[SwiftUI fundamental Tutorial] Image (0) | 2021.08.22 |
---|---|
[SwiftUI fundamental Tutorial] Text (0) | 2021.08.21 |
[SwiftUI fundamental Tutorial] WebView (0) | 2021.08.20 |
[SwiftUI fundamental Tutorial] State (0) | 2021.08.20 |
[SwiftUI fundamental Tutorial] Basic guide (0) | 2021.08.18 |