3

I am using SwiftUI and I have added Button in NavigationBar but I am unable to set action on that button. I tried these two approaches but failed.

Approach:1

.navigationBarTitle("\(task.label)")
.navigationBarItems(trailing: UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.actionName)))

But I am having this error here

Argument type 'UIBarButtonItem' does not conform to expected type 'View'

Approach:2

.navigationBarTitle("\(task.label)")
.navigationBarItems(trailing: NavigationBarButtonItem())

struct NavigationBarButtonItem : View {
    var body : some View {
        Button(action: {
            print("Button Tapped")
        }, label: {Text("Done")})
    }
}

Over here, This print statements never runs, although Button "Done" shows on Right side of NavigationBar, but action never works.

2 Answers 2

1

.navigationBarItems(trailing: UIBarButtonItem(...

the above is definitely incorrect - you try to pass UIKit object instead of expected View struct

The following one definitely works (tested with Xcode 11.2+)

NavigationView {
    // ... some view is here
    .navigationBarItems(trailing: Button("Done") { 
       print("Done something")
    })
}

Well, copy-pasted "as is" your code from Approach 2 works as well, so probably the reason is not in this code.

It is not provided all your code, but I can suppose you placed it outside NavigationView, but doc says:

/// This modifier only takes effect when this view is inside of and visible
/// within a `NavigationView`.
Sign up to request clarification or add additional context in comments.

Comments

0

navigationBarItems is deprecated for Approach:2.

For Approach:1 it would be:

.navigationBarTitle("\(task.label)")
.toolbar {
    ToolbarItem(placement: .navigationBarTrailing) {
        Button("Done") {
            action()
        }
    }
}

.toolbar is now the way to control the navigation bar.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.