[SwiftUI] Event(이벤트 처리) - Button, onDisappear

팔랑이·2023년 6월 9일
0

iOS/Swift

목록 보기
2/71
post-thumbnail

23-06-06


  1. Button(버튼)으로 기본적인 이벤트 처리
struct ContentView: View{
    var body: some View{
        Button(action:ButtonPressed){
            Text("Click me")
        }
    }

    func buttonPressed(){
        // 동작할 코드
    }
}

위와 같이 액션 함수를 지정하는 대신, 버튼 클릭시 실행될 코드를 클로저로 지정할 수도 있음.
struct ContentView: View{
    var body: some View{
        Button(action: {
            //동작할 코드
        }) {
            Text("Click me")
        }
    }
}

다음은 Image 뷰를 버튼으로 만드는 경우.

struct ContentView: View{
    var body: some View{
        Button(action: {
            print("hello")
        }) {
            Image(systemName: "square.and.arrow.down")
        }
    }
}




  1. onAppear, onDisappear 메서드
struct ContentView: View{
    var body: some View{
        Text("hello, World!")
        .onAppear(perform: {
            //뷰가 나타날 때 수행되는 코드
        })
        .onDisappear(perform: {
            //뷰가 사라질 때 수행되는 코드
        })
    }
}




  1. 커스텀 컨테이너 뷰 만들기

추후 추가예정


📚 참고도서
[SwiftUI 기반의 iOS 프로그래밍]

profile
정체되지 않는 성장

0개의 댓글