Language/Swift

SwiftUI를 이용한 메뉴 그리기 (Menu)

IFLA 2022. 12. 21. 12:37

 

SwiftUI 는 버튼에서 팝업 메뉴를 표시하기 위한 Menu 라는 전용 뷰를 제공한다. 메뉴에 표시할 항목을 제어하기 위한 다양한 버튼을 추가할 수 있다.

 

기본 코드

struct ContentView: View {
	var body: some View {
		Menu("Create") {
			Button("Cancel", action: {})
			Button("Search", action: {})
			Button("Add", action: {})
		}
	}
}

메뉴 중괄호 { } 안에 원하는 만큼 버튼을 추가할 수 있다.

 

실행 화면

 

메뉴에 Label 을 추가하여 메뉴 버튼에 텍스트와 아이콘을 추가할 수 있다.

struct ContentView: View {
	var body: some View {
		Menu("create") {
			Button("Cancel", action: {})

			Menu("More") {
				Button("Rename", action: {})
				
				Button(action: {
				}) {
					HStack {
						Text("Search")
						Image(systemName: "magnifyingglass.circle")
					}
				}
			}
		}
	]
}

 


개발자 Document

https://developer.apple.com/documentation/swiftui/menu

 

Apple Developer Documentation

 

developer.apple.com