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.
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:
- Moved
.frame(alignment: .trailing)
to theNavigationView
level - Added an
else
afterself.isButtonShown
that added aSpacer()
- Applied
.frame(alignment: .trailing)
to the BButton