SwiftUI에서 콘텍스트 메뉴 바인딩하기

최대 1 분 소요

콘텍스트 메뉴: 사용자가 뷰를 롱 프레스(long press) 했을 때 나타나는 메뉴

  • 구성 항목:
    • Text 뷰
    • Imgae 뷰(선택사항)
    • Button 뷰

콘텐트 뷰 준비하기

import SwiftUI

struct ContentView: View {
    
    @State private var foregroundColor: Color = Color.black
    @State private var backgroundColor: Color = Color.white
    
    var body: some View {
    
        Text("Hello, World!")
            .font(.largeTitle)
            .padding()
            .foregroundColor(foregroundColor)
            .backgroundColor(backgroundColor)
    }
}

포그라운드 색상 값과 백그라운드 색상 값을 저장하기 위한 상태 프로퍼티 추가
이를 이용해 Text 뷰의 색상 설정 제어


콘텍스트 메뉴 추가하기

contextMenu() 수정자를 사용

var body: some View {
    
    Text("Hello, World!")
        .font(.largeTitle)
        .padding()
        .foregroundColor(foregroundColor)
        .backgroundColor(backgroundColor)
        .contextMenu {
            Button(action: {
                self.foregroundColor = .black
                self.backgroundColor = .white
            }) {
                Text("Normal Colors")
                Image(systemName: "paintbrush")
            }
                
            Button(action: {
                self.foregroundColor = .white
                self.backgroundColor = .black
            }) {
                Text("Inverted Colors")
                Image(systemName: "paintbrush.fill")
            }
        }
}

action 클로저에 상태 프로퍼티에 할당된 값을 변경하는 코드 추가

스크린샷 2022-06-08 오전 2 48 00 스크린샷 2022-06-08 오전 2 48 21

카테고리:

업데이트: