2

I have a SwiftUI view that looks like this (simplified for privacy reasons):

var body: some View {

    HStack {

        Button(action: {

            self.completed.toggle()

        }) {

            Text(self.title)

        }

        NavigationLink(destination: DetailView(task: self.task)) {

            Text(self.title)

        }

    }

}

The navigation works just fine, and the DetailView has the updated status (toggle just toggles the status), however when I go back to the main view, the status is not updated. Why is this?

And I need the button to act differently to the text - is this possible? I want the button press to perform the button action, and the rest of the row to act as the NavigationLink. How can I do this?

The self.completed is a CompletionStatus class that is an ObservableObject, with a @Published property status. task is @State of type Task, which contains the completed (CompletionStatus) property. Please let me know if I can provide any more information.

Here are the Task and CompletionStatus structs and classes respectively:

struct Task: Identifiable {
    let id: UUID()
    var title: String
    var description: String
    @ObservedObject var completed: CompletionStatus
}

class CompletionStatus: ObservableObject {
    @Published var status: Bool

    init(_ defaultValue: Bool) {

        self.status = defaultValue

    }

    func toggle() -> CompletionStatus {

        self.status = !self.status
        return self

    }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • It would probably help to see your `Task` and `CompletionStatus` classes as well. – graycampbell Aug 15 '19 at 02:18
  • Edited @graycampbell. – Jack Bashford Aug 15 '19 at 02:21
  • 1
    For the button its easy. Use a onTapGesture on something (e.g. Image) instead of a button. – Marc T. Aug 15 '19 at 05:14
  • Thanks @MarcT., but that's working fine - the issue is that whenever I click on the Text, not the Button, the button's action is fired. Sorry if I didn't make that clear enough. – Jack Bashford Aug 15 '19 at 07:39
  • Thanks @MarcT. - that works perfectly! Thank you so much! That fixed my problem, and making `completed` to `@ObservedObject` made sure it updated. If you post it as an answer, I'll accept it. Thank you so much! – Jack Bashford Aug 15 '19 at 08:01

0 Answers0