charlesj
charlesj

Reputation: 33

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

Upvotes: 3

Views: 1002

Answers (1)

Matthaus Woolard
Matthaus Woolard

Reputation: 2408

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()
    }
 }
}

Upvotes: 2

Related Questions