article

Thursday, May 5, 2022

Swiftui custom navigationbar

Swiftui custom navigationbar

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            List(0..<20) { rs in
                NavigationLink(destination: DetailsView().navigationBarBackButtonHidden(true)) {
                    Text("Details Custom Navigation Bar \(rs)")
                }
            }
            .navigationBarTitle("Custom Navigation Bar")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
DetailsView.swift
 
//
//  DetailsView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailsView: View {
    @Environment(\.presentationMode) var presentationMode
    @State var items = [Item]()
    
    var body: some View {
        //Wrap ContentView into a NavigationView
            List(items) { item in
                Text(item.name)
            }
            //Add navigation bar title
            .navigationTitle("Todo List")
            //Initialize toolbar
            .toolbar(content: {
                //Declare one ToolBarItem for each navigation bar button and set the position
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                        self.presentationMode.wrappedValue.dismiss()    
                    }) {
                        Image(systemName: "chevron.backward")
                            .imageScale(.large)
                    }
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                            addTask()
                    }) {
                        Image(systemName: "plus.circle")
                            .imageScale(.large)
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                            removeTask()
                    }) {
                        Image(systemName: "minus.circle")
                            .imageScale(.large)
                    }
                }
            })
    }
    
    func addTask() {
        let item = Item(id: items.count+1, name: "Sample Todo List")
        items.append(item)
    }
    
    func removeTask() {
        items.removeLast()
    }
}

struct DetailsView_Previews: PreviewProvider {
    static var previews: some View {
        DetailsView()
    }
}


struct Item : Identifiable {
    var id : Int
    var name : String
}

Related Post