问题
I already have a toggle set up as in the image below to toggle the image on/off or pass / fail. I am trying to add a third state using a long press gesture to the image which will turn the image grey with a slash icon. I have achieved this in the text element as at is doesn't have an bool condition, but after much searching can't figure out how to achieve this with the image.
What I am aiming for is something along the lines of:
Image(systemName: isPressed ? "checkmark.circle.fill" : "x.circle.fill" || isLongPressed ? "checkmark.circle.fill" : "slash.circle.fill")
Though I know this is not correct.
struct element: View {
var section: CleaningElements = courseSections[0]
@State private var isPressed = true
@State private var isLongPressed = true
var body: some View {
HStack(alignment: .top) {
Button(action: {
self.isPressed.toggle() }) {
Image(systemName: isPressed ? "checkmark.circle.fill" : "x.circle.fill")
.font(.system(size: 20))
.foregroundColor(isPressed ? .green : .red)
.frame(width: 36, height: 36)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(section.color))
}
Text(section.title)
.font(.subheadline)
.bold()
.opacity(isLongPressed ? 1.0 : 0.3)
.foregroundColor(isLongPressed ? Color.primary : Color.secondary)
.onLongPressGesture {
self.isLongPressed.toggle()
}
Spacer()
}
.padding(3)
}
}
回答1:
Here is a demo (with simplified your code) of possible solution - keep button for highlight but actions handle but custom gestures. Tested with Xcode 12.1 / iOS 14.1
struct element: View {
@State private var isPressed = false
@State private var isLongPressed = false
var body: some View {
Button(action: {}) {
Group {
if isLongPressed {
Image(systemName: "minus.circle")
.foregroundColor(.gray)
} else {
Image(systemName: isPressed ? "checkmark.circle.fill" : "x.circle.fill")
.foregroundColor(isPressed ? .green : .red)
}
}
.font(.system(size: 20))
.frame(width: 36, height: 36)
.background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Color.yellow))
.gesture(TapGesture().onEnded {
isLongPressed = false
self.isPressed.toggle()
})
.gesture(LongPressGesture().onEnded { _ in
isLongPressed = true
})
}
}
}
来源:https://stackoverflow.com/questions/64953772/is-there-a-way-to-add-a-third-toggle-option-to-an-on-off-state-by-onlongpressge