SwiftUI: navigationBarItems missing on first render - navigationbar

I'm seeing a strange issue that I was able to reproduce with a small sample. If you have a detail view that has navigationBarItems set, and that detail is the second view pushed on a navigation stack, the items do not show up when you get to the detail page. Here is the sample:
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: MiddleTestView()) {
Text("Push View")
}
}
}
}
}
struct MiddleTestView: View {
var body: some View {
VStack {
NavigationLink(destination: TestView()) {
Text("Push Another View")
}
}
}
}
struct TestView: View {
var body: some View {
VStack {
Text("Testing 1, 2, 3")
}
.navigationBarItems(leading: Button("Test") { print("pressed") })
}
}
If anything causes the TestView to re-render, then the button will show, for instance if the TestView does this:
struct TestView: View {
#State var hasChanges = false
var body: some View {
VStack {
Text("Testing 1, 2, 3")
Button("Toggle") { hasChanges = !hasChanges }
}
.navigationBarItems(leading: Button(hasChanges ? "Test1" : "Test2") { print("pressed") })
}
}
Then pressing the "Toggle" button once will cause the navigationBarItems to appear, and they will stay there until the view is dismissed. Additionally, if the TestView is shown first, instead of the MiddleTestView, then there is no problem with the navigationBarItems. I cannot see any reason for this behavior, it seems like a pretty glaring bug that makes working with navigation stacks in SwiftUI fundamentally broken, unless I'm missing something. Does anyone have any insight into what is going on here or how to get around it?

Related

How to bind an action to the navigationview back button?

Hi I would like to bind an action to the Back button in the navigationview toolbar, is it possible?
picture about the situation
var body: some View {
List {
ForEach(mainViewModel.items) { item in
NavigationLink(destination: EditTaskView(item: item)) {
HStack {
ListRowView(item: item)
You can't bind directly to the back button, but you can have the navigation link itself be activated based on state, and then listen to the change of the state value like so. Do note that this requires that you manage the setting of state to true (no auto tap like with the default initializer)
struct ContentView: View {
#State private var showingNavView = false
var body: some View {
NavigationView {
List {
NavigationLink("Sub View", isActive: $showingNavView) {
SubView()
}.onTapGesture {
showingNavView = true
}.onChange(of: showingNavView) { newValue in
print(newValue) // Will change to false when back is pressed
}
}
}
}
}
struct SubView: View {
var body: some View {
ZStack {
Color.green
Text("Cool Beans")
}
}
}

How to put an element in front of a ForEach with a ZStack without making it overlapped

I am trying to create a layout in which there is a list of elements, and a button to add more elements in front of it. I know I could put it in the navigation bar, but that's not the graphic look I'd like to achieve. However, if I put those two elements inside a ZStack, the ForEach becomes overlapped, even though it's within a VStack. How can I solve this?
import SwiftUI
struct ContentView: View {
let arrayTest = ["Element 1", "Element 2", "Element 3"]
var body: some View {
NavigationView {
ZStack {
VStack {
ForEach(arrayTest, id: \.self) { strings in
Text(strings)
}
}
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
//AddView
}) {
Image(systemName: "plus")
.background(Circle().foregroundColor(.yellow))
}.padding(.trailing, 20)
.padding(.bottom, 20)
}
}
}
}
}
}
Edit: To be more precise, I would like the button to be over the ForEach, because if I used a VStack and the list of elements was very long, the user would have to scroll all the way to the bottom to find the button. With a ZStack, it would always be visible no matter the point of the list the user is at.
Here is one way of using overlay, see example in code:
struct ContentView: View {
#State private var arrayTest: [String] = [String]()
var body: some View {
NavigationView {
Form { ForEach(arrayTest, id: \.self) { strings in Text(strings) } }
.navigationTitle("Add Elements")
}
.overlay(
Button(action: { addElement() })
{ Image(systemName: "plus").font(Font.largeTitle).background(Circle().foregroundColor(.yellow)) }.padding()
, alignment: .bottomTrailing)
.onAppear() { for _ in 0...12 { addElement() } }
}
func addElement() { arrayTest.append("Element " + "\(arrayTest.count + 1)") }
}

SwiftUI: Button in Form

I am creating a Form in SwiftUi with a section that is including a flexible number of instruction.
Next to the last instruction TextField, I am showing a "+"-Button that is extending the instructions array with a new member:
var body: some View {
NavigationView {
Form {
...
Section(header: Text("Instructions")) {
InstructionsSectionView(instructions: $recipeViewModel.recipe.instructions)
}
...
struct InstructionsSectionView: View {
#Binding var instructions: [String]
var body: some View {
ForEach(instructions.indices, id: \.self) { index in
HStack {
TextField("Instruction", text: $instructions[index])
if(index == instructions.count-1) {
addInstructionButton
}
}
}
}
var addInstructionButton: some View {
Button(action: {
instructions.append("")
}) {
Image(systemName: "plus.circle.fill")
}
}
}
Now the problem is, that the button click-area is not limited to the picture but to the whole last row. Precisely the part just around the textField, meaning if I click in it, I can edit the text, but if I click on the border somewhere, a new entry is added.
I assume that this is specific to Form {} (or also List{}), since it does not happen if I use a Button next to a text field in a "normal" set-up.
Is there something wrong with my code? Is this an expected behaviour?
I am not sure why border is getting tappable, but as a workaround I used plainButtonStyle and that seems to fix this issue, and keeps functionality intact .
struct TestView: View {
#State private var endAmount: CGFloat = 0
#State private var recipeViewModel = ["abc","Deef"]
var body: some View {
NavigationView {
Form {
Section(header: Text("Instructions")) {
InstructionsSectionView(instructions: $recipeViewModel)
}
}
}
}
}
struct InstructionsSectionView: View {
#Binding var instructions: [String]
var body: some View {
ForEach(instructions.indices, id: \.self) { index in
HStack {
TextField("Instruction", text: $instructions[index])
Spacer()
if(index == instructions.count-1) {
addInstructionButton
.buttonStyle(PlainButtonStyle())
.foregroundColor(.blue)
}
}
}
}
var addInstructionButton: some View {
Button(action: {
instructions.append("")
}) {
Image(systemName: "plus.circle.fill")
}
}
}

swiftui open view from menu button

I am trying to do something very basic, but I have been through the official tutorials, and through dozens of stack overflow posts. I am trying to open an activity from a menu button. I do want the standard navigation back arrow when I do this.
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Text("Hello World!")
.toolbar {
ToolbarItem(placement: .primaryAction) {
Menu {
Button(action: {
Activities()
}) {
Label("Activities", systemImage: "doc")
}
"Activities()" is my view. When I do this nothing happens. I have read in other posts that you cannot have a navigation link in a menu either, which would be fine if that worked. How do I programmatically open up a view so the back arrow works?
Thank you
In this case where you want to open a view but can't use a NavigationLink directly you can use it in another place and activate it programmatically from the button via a State property:
#State private var isShowingDetailView = false
var body: some View {
NavigationView {
VStack(alignment: .leading) {
NavigationLink(destination: Activities(), isActive: $isShowingDetailView) {
EmptyView()
}
Text("Hello World!")
.toolbar {
ToolbarItem(placement: .primaryAction) {
Menu {
Button(action: {
isShowingDetailView = true
}) {
Label("Activities", systemImage: "doc")
}
}
}
}
}
}

How do you make a Button conditionally hidden or disabled?

How do I toggle the presence of a button to be hidden or not?
We have the non-conditional .hidden() property; but I need the conditional version.
Note: we do have the .disabled(bool) property available, but not the .hidden(bool).
struct ContentView: View {
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foreggroundColor(Color.white)
.cornerRadius(10)
.hidden() // ...I want this to be toggled.
}
}
}
}
I hope hidden modifier gets argument later, but since then, Set the alpha instead:
#State var shouldHide = false
var body: some View {
Button("Button") { self.shouldHide = true }
.opacity(shouldHide ? 0 : 1)
}
For me it worked perfectly to set the frame's height to zero when you do not want to see it. When you want to have the calculated size, just set it to nil:
SomeView
.frame(height: isVisible ? nil : 0)
If you want to disable it in addition to hiding it, you could set .disabled with the toggled boolean.
SomeView
.frame(height: isVisible ? nil : 0)
.disabled(!isVisible)
You can utilize SwiftUI's new two-way bindings and add an if-statement as:
struct ContentView: View {
#State var shouldHide = false
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
if !self.$shouldHide.wrappedValue {
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(10)
}
}
}
}
}
The benefit of doing this over setting the opacity to 0 is that it will remove the weird spacing/padding from your UI caused from the button still being in the view, just not visible (if the button is between other view components, that is).
all the answers here works specifically for a button to be hidden conditionally.
What i think might help is making a modifier itself conditionally e.g:
.hidden for button/view, or maybe .italic for text, etc..
Using extensions.
For text to be conditionally italic it is easy since .italic modifier returns Text:
extension Text {
func italicConditionally(isItalic: Bool) -> Text {
isItalic ? self.italic() : self
}
}
then applying conditional italic like this:
#State private var toggle = false
Text("My Text")
.italicConditionally(isItalic: toggle)
However for Button it is tricky, since the .hidden modifier returns "some view":
extension View {
func hiddenConditionally(isHidden: Bool) -> some View {
isHidden ? AnyView(self.hidden()) : AnyView(self)
}
}
then applying conditional hidden like this:
#State private var toggle = false
Button("myButton", action: myAction)
.hiddenConditionally(isHidden: toggle)
You can easily hide a view in SwiftUI using a conditional statement.
struct TestView: View{
#State private var isVisible = false
var body: some View{
if !isVisible {
HStack{
Button(action: {
isVisible.toggle()
// after click you'r view will be hidden
}){
Text("any view")
}
}
}
}
}
It isn't always going to be a pretty solution, but in some cases, adding it conditionally may also work:
if shouldShowMyButton {
Button(action: {
self.imageDetectionVM.detect(self.selectedImage)
}) {
Text("Button")
}
}
There will be an issue of the empty space in the case when it isn't being shown, which may be more or less of an issue depending on the specific layout. That might be addressed by adding an else statement that alternatively adds an equivalently sized blank space.
#State private var isHidden = true
VStack / HStack
if isHidden {
Button {
if !loadVideo(),
let urlStr = drill?.videoURL as? String,
let url = URL(string: urlStr) {
player = VideoPlayerView(player: AVPlayer(), videoUrl: url)
playVideo.toggle()
}
} label: {
Image(playVideo ? "ic_close_blue" : "ic_video_attached")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 50)
}
.buttonStyle(BorderlessButtonStyle())
}
.onAppear {
if shouldShowButton {
isHidden = false
} else {
isVideoButtonHidden = true
}
}

Resources