SwiftUI 编辑模式下更改视图

4

我试图根据编辑模式更改视图状态,当正在编辑时隐藏视图并在不编辑时显示视图,当我使用"on change"并打印编辑模式值时它可以工作,但是在处理视图时它就不能工作。

struct TaskStateMark_Row: View {
    
    @ObservedObject var task: Task
    @Environment(\.editMode) private var editMode
    
    var body: some View {
        Group {
        // Show and hide the view according to edit mode state
            if let editMode = editMode?.wrappedValue {
                if editMode == .inactive {
                    taskState
                        .onTapGesture(perform: onTapAction)
                }
            }
        }
    }
    
    
    
    private var taskState: some View {
        Group {
            if task.isCompleted {
                completedState
            } else {
                incompletedState
            }
        }
        .frame(width: 44, height: 44)
    }
    
    private var incompletedState: some View {
        ZStack{
            fillCircle
            circle
        }
    }
    
    private var circle: some View {
        Image(systemName: "circle")
            .font(.system(size: 24))
            .foregroundColor(task.wrappedPriority.color)
    }
    
    private var fillCircle: some View {
        Image(systemName: "circle.fill")
            .font(.system(size: 24))
            .foregroundColor(task.wrappedPriority.color.opacity(0.15))
    }
    
    private var completedState: some View {
        Image(systemName: "checkmark.circle.fill")
            .symbolRenderingMode(.palette)
            .foregroundStyle(.white, task.wrappedPriority.color)
            .font(.system(size: 24))
    }    
    
}
1个回答

3
我在下面的链接中的开发者文档中找到了答案:

https://developer.apple.com/documentation/swiftui/editmode

这是代码:
@Environment(\.editMode) private var editMode
@State private var name = "Maria Ruiz"

var body: some View {
    Form {
        if editMode?.wrappedValue.isEditing == true {
            TextField("Name", text: $name)
        } else {
            Text(name)
        }
    }
    .animation(nil, value: editMode?.wrappedValue)
    .toolbar { // Assumes embedding this view in a NavigationView.
        EditButton()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接