1
votes

I have a Form Section which I want to show some text and the EditButton() within the same header line as shown below:

enter image description here

The issue occurs when I tap the button whenever its embedded within an HStack. The button text toggles between "Edit" and "Done", yet it doesn't call the onDelete() action for the rows. However, it does work if it's solely assigned as the header, footer, or embedded in a Group arrangement for the Section.

Section(header: HStack { Text("Recent"); Spacer(); EditButton() }) {

    ForEach(locationsList, id:\.self) { location in

        Text("\(location.name)")

    }.onDelete(perform: deleteLocation)
}

Does anyone have any reasoning why my ForEach loop wouldn't be responding to the button when it's embedded in a view arrangement such as an HStack, VStack, or even a ZStack? Is there an alternative to achieve the same layout for the header without using an HStack?

2

2 Answers

1
votes

Looks like it's because EditButton is inside list. It works if to move EditButton out of List, like below

enter image description here

VStack {
    HStack { Text("Recent"); Spacer(); EditButton() }
        .padding(.horizontal)
        .background(Color(UIColor.systemGray3))
    List{
            ForEach(locationsList, id:\.self) { location in
            ...
0
votes

The EditButton presumably writes to the binding that gets handed down to it in the form of the environment value editMode:

var editMode: Binding<EditMode>? { get set }

The Form/List possibly manages its own EditMode state, a binding to which is propagated to all of its child EditButtons via the environment, except that for some reason an intermediary Z/V/HStack interferes with this propagation. Instead use your own state:

@State var editMode: EditMode = .inactive

...

  Form {
    Section(header: HStack { 
      Text("Recent")
      Spacer()
      EditButton().environment(\.editMode, $editMode) 
    }) {
      ...
    }
  }
  .environment(\.editMode, $editMode)

The Form now has the same editMode environment as the EditButton, bypassing any HStack quirks. I'm guessing that Form/List simply honors the editMode passed to them as long as it's not nil, or something like that.

The upside with doing it this way is that you don't have to change your view hierarchy.