使用tvOS
我试图有一个上下文菜单出现,当用户长按一个按钮。
如果我不使用。buttonstyle()或者使用一个内置的buttonStyles, contextMenu就会出现。
但是,我想使用自定义按钮样式。当我这样做时,. contextmenu被忽略。
下面是我的基本代码:import SwiftUI
struct TestButtonStyle: ButtonStyle {
@Environment(.isFocused) var focused: Bool
@State private var isFocused: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.frame(height: 50)
.background(RoundedRectangle(cornerRadius: 20).fill(isFocused ? .red.opacity(0.75) : .clear))
.onChange(of: focused) { hasFocus in
if hasFocus {
isFocused = true
} else {
isFocused = false
}
}
}
}
struct ContentView: View {
var body: some View {
HStack {
Button {
print("Button 1 Pressed")
} label: {
Text("Button 1")
}
.buttonStyle(TestButtonStyle())
.contextMenu {
Button {
//
} label: {
Text("Option 1")
}
Button {
//
} label: {
Text("Option 2")
}
}
Button {
print("Button 2 Pressed")
} label: {
Text("Button 2")
}
.contextMenu {
Button {
//
} label: {
Text("Option 3")
}
Button {
//
} label: {
Text("Option 4")
}
}
.buttonStyle(TestButtonStyle())
}
}
}
有人遇到这个问题并解决了吗?谢谢。
我找到了一个解决这个问题的方法。
struct MoviesBlankButtonStyle: PrimitiveButtonStyle {
@Environment(.isFocused) var focused: Bool
@State private var isFocused: Bool = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.compositingGroup()
.padding(.all, 9)
.focusable(true, onFocusChange: { focused in
if focused {
isFocused = true
} else {
isFocused = false
}
})
.background(RoundedRectangle(cornerRadius: 20).fill(isFocused ? .red : .clear).opacity(0.7 ))
.foregroundColor(isFocused ? .white : .white)
.onTapGesture(perform: configuration.trigger)
}
}