iosswiftuiios13ios-navigationviewnavigationbaritems

Maintain navigation item button alignment in SwiftUI as second button is added & removed


I have a scenario where there will be one or two trailing buttons based upon some criteria. I would like to have it such that the buttons always align to trailing for visual consistency, but so far, they appear to center align, regardless of what I do.

Below is a minimum example showing this:

import SwiftUI

struct ContentView: View {
    @State private var isButtonShown = true

    var body: some View {
        NavigationView {
            Button(action: {
                self.isButtonShown.toggle()
            }, label: {
                Text(self.isButtonShown ? "Hide Button" : "Show Button")
                     })
                .navigationBarItems(trailing:
                    HStack {
                        if self.isButtonShown {
                            Button(action: {
                                print("A tapped")
                            }, label: {
                                Text("A")
                            })
                            Spacer(minLength: 30)
                        }

                        Button(action: {
                            print("B tapped")
                        }, label: {
                            Text("B")
                        })
                    }
                    .frame(alignment: .trailing)
                )
        }
    }
}

And a video that shows what happens when I select the button.

enter image description here

My goal is to have B remain in the same position, regardless of whether or not A is shown.

Finally, I tried a few other items:


Solution

  • It is know issue in SwiftUI 1.0

    SwiftUI 2.0

    The solution based on new .toolbar does not have it. Tested with Xcode 12 / iOS 14

    demo

    struct ContentView: View {
        @State private var isButtonShown = true
    
        var body: some View {
            NavigationView {
                Button(action: {
                    self.isButtonShown.toggle()
                }, label: {
                    Text(self.isButtonShown ? "Hide Button" : "Show Button")
                         })
                .toolbar {
                    ToolbarItem(placement: .primaryAction) {
                        if self.isButtonShown {
                            Button(action: {
                                print("A tapped")
                            }, label: {
                                Text("A")
                            })
                        }
                    }
    
                    ToolbarItem(placement: .primaryAction) {
                        Button(action: {
                            print("B tapped")
                        }, label: {
                            Text("B")
                        })
                    }
                }
            }
        }
    }