如何在SwiftUI ForEach内容中将多个按钮操作分开? [英] How do I keep multiple button actions separate in SwiftUI ForEach content?

查看:65
本文介绍了如何在SwiftUI ForEach内容中将多个按钮操作分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,其中带有一个复选框,一个标题和一个计时器图标:

I have a list of items with a checkbox a title and a timer icon:

该复选框是一个按钮,而计时器图标是一个具有唯一操作关联的按钮.但是,如果我点击单元格内的任何位置,它将同时触发两个按钮动作.旨在使它们彼此独立运行,以及单元中的水龙头独立运行.如何修改以下代码以使操作分开?

The checkbox is a button and the timer icon is a button that have unique actions associated with them. However, if I tap anywhere inside the cell, it triggers both button actions simultaneously. It is intended that they operate independently of each other as well as the tap in the cell. How do I modify the following code to keep the actions separate?

List {
      ForEach(tasks, id: \.self) { task in
            HStack {

                Button(action: {
                    task.isComplete.toggle()
                    try? self.moc.save()
                    print("Done button tapped")
                }) {
                    Image(systemName: task.isComplete ? "square.fill" : "square")
                }
                .padding()

                Text(task.name ?? "Unknown Task")
                Spacer()

                Button(action: {
                    print("timer button tapped")
                }) {
                    Image("timer")
                }    
            }
        }
        .onDelete(perform: deleteTask)
    }

推荐答案

这是List的默认行为,它标识行中的Button并使整个行处于活动状态,而改为使用 .onTapGesture 如下

This is default behaviour of List, it identifies Button in row and makes entire row active, use instead .onTapGesture as below

List {
      ForEach(tasks, id: \.self) { task in
            HStack {

                Image(systemName: task.isComplete ? "square.fill" : "square")
                .padding()
                .onTapGesture {
                    task.isComplete.toggle()
                    try? self.moc.save()
                    print("Done button tapped")
                }

                Text(task.name ?? "Unknown Task")
                Spacer()

                Image("timer")
                .onTapGesture {
                    print("timer button tapped")
                }    
            }
        }
        .onDelete(perform: deleteTask)
    }

这篇关于如何在SwiftUI ForEach内容中将多个按钮操作分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆