Devlog
article thumbnail

위 글은 유튜브 정대리님의 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)
               }
            }
        }
}

MyStackView에다가 isActivated를 넘겨줌

 

 

 

네비게이션 뷰에서 바인딩하기

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))

 

 

 

 

 

 

 

profile

Devlog

@덩이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그