A different way of coding navigationBarItems

,
keyboard, pens and notepad

I have been following along with Paul Hudson’s 100 Days of SwiftUI course. A really excellent introduction to SwiftUI if you are looking for one. However, there are some patterns in SwiftUI that I find particularly hard to read at the moment and wondered if there was a way to change this.

For instance in the view below, Paul adds a button to the top right of the view which displays a plus symbol and allows a new view to show as a sheet.

NavigationView {
    Text("Count: \(books.count)")
        .navigationBarTitle("Bookworm")
        .navigationBarItems(trailing: Button(action: {
            self.showingAddScreen.toggle()
        }) {
            Image(systemName: "plus")
        })
        .sheet(isPresented: $showingAddScreen) {
            AddBookView().environment(\.managedObjectContext, self.moc)
    }
}

For me the code relating to the creation of the Add button makes the navigationBar modifiers harder to read. I therefore tried the following code:

NavigationView {
    Text("Count: \(books.count)")
        .navigationBarTitle("Bookworm")
        .navigationBarItems(trailing: addButton())
        .sheet(isPresented: $showingAddScreen) {
            AddBookView().environment(\.managedObjectContext, self.moc)
        }
}

This kept the modifiers easier to read and I then moved the button creation code to its own method

func addButton() -> some View {
    return Button(action: {
        self.showingAddScreen.toggle()
    }) {
        Image(systemName: "plus")
    }
}

Let me know what you think, does it make the code more readable, or just add a layer of complexity that is unwanted? Use the comments below or tweet me

Photo by Jess Bailey on Unsplash

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.