SwiftUI의 콘텍스트 메뉴
SwiftUI의 콘텍스트 메뉴
콘텍스트 메뉴는 생소하게 들리지만 사용자가 뷰를 길게 눌렀을 때 나타나는 메뉴를 의미한다 일반적으로 Text뷰와 Image 뷰를 포함하고 선택했을 때 동작을 수행하도록 구성된 Button 뷰를 포함한다
콘텐츠 뷰 만들기
롱 프레스를 할 뷰를 생성한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import SwiftUI
struct ContentView: View {
@State private var forgroundColor: Color = .red
@State private var backgroundColor: Color = .yellow
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.foregroundColor(forgroundColor)
.background(backgroundColor)
}
.padding()
}
}
콘텍스트 메뉴 추가
이제 contextMenu 수정자를 통해서 롱 프레스 시 보여줄 버튼들과 그 행동을 설정한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import SwiftUI
struct ContentView: View {
@State private var forgroundColor: Color = .red
@State private var backgroundColor: Color = .yellow
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.foregroundColor(forgroundColor)
.background(backgroundColor)
.contextMenu {
Button(action: {
self.backgroundColor = .blue
self.forgroundColor = .black
}) {
Text("Change Color")
Image(systemName: "paintbrush")
}
Button(action: {
self.backgroundColor = .red
self.forgroundColor = .yellow
}) {
Text("Invert Color")
Image(systemName: "paintbrush")
}
}
}
.padding()
}
}
콘텍스트 메뉴는 레이아웃상의 뷰에서 롱 프레스 제스처를 할 때 나타나다 콘텍스트 메뉴는 모든 뷰타입에 추가될 수 있고 contextMenu 수정자를 통해서 구현된다 일반적으로 Text와 Image를 포함하고 Button뷰 형태를 취한다
This post is licensed under CC BY 4.0 by the author.