有没有办法通过 .onLongPressGesture 将第三个切换选项添加到开/关状态?

2023-12-14

我已经设置了一个切换开关,如下图所示,可以打开/关闭图像或通过/失败。 我正在尝试使用长按手势向图像添加第三种状态,这会将图像变成带有斜杠图标的灰色。 我已经在文本元素中实现了这一点,因为 at is 没有 bool 条件,但经过多次搜索后无法弄清楚如何使用图像来实现这一点。

我的目标是:

Image(systemName: isPressed ? "checkmark.circle.fill" : "x.circle.fill" || isLongPressed ? "checkmark.circle.fill" : "slash.circle.fill")

虽然我知道这是不正确的。

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)
    }
}

On/Off, or N/A states


这是一个可能的解决方案的演示(简化了您的代码) - 保留按钮以突出显示,但操作处理自定义手势。使用 Xcode 12.1 / iOS 14.1 进行测试

demo

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
            })
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法通过 .onLongPressGesture 将第三个切换选项添加到开/关状态? 的相关文章

随机推荐