Search code examples
swiftswiftuiswiftui-button

SwiftUI - Dynamic Edit Button on Nav Bar


I'm fairly new to Swift/SwiftUI - I'm working on a simple to-do list app and trying to make a Nav bar button that changes from the built-in Edit button to a custom button depending on a state variable.

I attempted this using a ternary operator like below

@State var addingItems: Bool = false

...

}.navigationBarItems(trailing: self.addingItems ? Button("Done", action: submitItems) : EditButton())

Each of the buttons work here individually, but Swift will not let me mix them like this. I get a mismatched types error

Result values in '? :' expression have mismatching types 'Button<Text>' and 'EditButton'

Is there a way to make this work outside of writing a custom Edit button?

Thanks


Solution

  • If you are ok with just supporting iOS 14+ you should use the toolbar api

    .toolbar {
     ToolbarItem(placement: .primary) {
        if self.addingItems {
           Button("Done", action: submitItems)
        } else {
           EditButton()
        }
     }
    }