새소식

iOS/SwiftUI

[SwiftUI] How to use ContextMenu in SwifUI

  • -

[참고 영상]

https://youtu.be/3jjQ6WASGIw


[학습 목표]

ContextMenu란 카드나 버튼을 꾹 눌렸을때 해당 버튼이나 카드에서 추가 옵션이 뜨면서 수정이나 삭제등의 기능이 보이는 메뉴이다.

이와 같은 ContextMenu를 SwiftUI에서 구현해서 사용해보자!


[구현 방법]

SwiftUI에서의 ContextMenu는 UIKit과는 다르게 이미 구현이 되어 있어서 매우 쉽게 사용이 가능하다.

그럼 이제부터 어떻게 ContextMenu를 사용하는지 살펴보자.

 

1. 우선은 ContextMenu를 사용하기 위해서 꾹 눌려야 하는 카드를 만들어보자.

@State var backgroundColor: Color = Color(.blue) VStack(alignment: .leading, spacing: 10.0) { Image(systemName: "house.fill") .font(.title) Text("Swiftul Thinking") .font(.headline) Text("how to use Context Menu") .font(.subheadline) } .foregroundColor(.white) .padding(30) .background(backgroundColor.cornerRadius(30))

Vstack을 이용해서 만들어보았다. 제일 위에 있는 State 변수를 이용해서 backgroundColor의 색깔을 지정해 두었다.

<구현 모습>

 

2. 이제부터 해당 Vstack에 ContextMenu를 넣어주도록 하자.

.contextMenu(menuItems: { Button { backgroundColor = .yellow } label: { Label("Share Post 1", systemImage: "flame.fill") } Button { backgroundColor = .red } label: { Text("Report Post 2") } Button { backgroundColor = .green } label: { HStack{ Text("Like Post") Image(systemName: "heart.fill") } } })

해당 코드는 contextMenu가 일어나면 3개의 버튼이 생기고 첫번째 버튼을 누르면 yellow 두번째 버튼은 red 세번째 버튼은 green으로 변하게 만드는 코드이다.

 

그렇기에 위와 같은 변화가 일어날 수가 있다.

 

<전체 코드>

import SwiftUI struct ContextMenuController: View { @State var backgroundColor: Color = Color(.blue) var body: some View { VStack(alignment: .leading, spacing: 10.0) { Image(systemName: "house.fill") .font(.title) Text("Swiftul Thinking") .font(.headline) Text("how to use Context Menu") .font(.subheadline) } .foregroundColor(.white) .padding(30) .background(backgroundColor.cornerRadius(30)) .contextMenu(menuItems: { Button { backgroundColor = .yellow } label: { Label("Share Post 1", systemImage: "flame.fill") } Button { backgroundColor = .red } label: { Text("Report Post 2") } Button { backgroundColor = .green } label: { HStack{ Text("Like Post") Image(systemName: "heart.fill") } } }) } }

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.