
UIMenu의 appendPreferences 메서드는 Preference Items를 추가하는 데 사용됩니다.
Preference Items를 추가하려면, 우선 Preference Store를 생성해야 합니다. Preference Store는 Preference Items의 기본 설정값을 관리합니다.
#hostingforum.kr
swift
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.environment(.uiPreferences, .init())
}
}
}
struct ContentView: View {
@Environment(.uiPreferences) var preferences
var body: some View {
Button(action: {
// Context Menu를 띄우는 코드
}) {
Text("Button")
}
.contextMenu {
HStack {
Button(action: {
// Preference Item 1을 클릭했을 때 동작
}) {
Text("Preference Item 1")
}
Button(action: {
// Preference Item 2을 클릭했을 때 동작
}) {
Text("Preference Item 2")
}
}
}
}
}
Preference Store를 생성하려면, Preference Items를 정의해야 합니다. Preference Items는 PreferenceKey를 사용하여 정의됩니다.
#hostingforum.kr
swift
struct PreferenceKey: PreferenceKey {
static var defaultValue: Bool = false
static func reduce(value: inout Bool, nextValue: () -> Bool) {
value = nextValue()
}
}
struct ContentView: View {
@Environment(.uiPreferences) var preferences
var body: some View {
Button(action: {
// Context Menu를 띄우는 코드
}) {
Text("Button")
}
.contextMenu {
HStack {
Button(action: {
preferences[PreferenceKey.self] = true
}) {
Text("Preference Item 1")
}
Button(action: {
preferences[PreferenceKey.self] = false
}) {
Text("Preference Item 2")
}
}
}
}
}
Preference Items의 기본 설정값을 구현하려면, Preference Store의 defaultValue를 사용합니다.
#hostingforum.kr
swift
struct PreferenceKey: PreferenceKey {
static var defaultValue: Bool = true
static func reduce(value: inout Bool, nextValue: () -> Bool) {
value = nextValue()
}
}
이제 Preference Items를 추가하는 코드는 다음과 같습니다.
#hostingforum.kr
swift
struct ContentView: View {
@Environment(.uiPreferences) var preferences
var body: some View {
Button(action: {
// Context Menu를 띄우는 코드
}) {
Text("Button")
}
.contextMenu {
HStack {
Button(action: {
preferences[PreferenceKey.self] = true
}) {
Text("Preference Item 1")
}
Button(action: {
preferences[PreferenceKey.self] = false
}) {
Text("Preference Item 2")
}
}
}
}
}
이 코드는 Preference Items를 추가하고, Preference Items의 기본 설정값을 구현합니다.
2025-06-07 09:34