struct NavigationBarProxy: UIViewControllerRepresentable {
    var callback: (UIView, UINavigationBar) -> Void
    
    private let proxyController = ViewController()
    
    func makeUIViewController(context: Context) -> UIViewController {
        proxyController.callback = callback
        return proxyController
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
    }
    
    typealias UIViewControllerType = UIViewController
    
    private class ViewController: UIViewController {
        var callback: (UIView, UINavigationBar) -> Void = { _, _ in }
        
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if let navigationController = self.navigationController {
                self.callback(navigationController.view, navigationController.navigationBar)
            }
        }
        
    }
}

 

[사용방법]

struct ContentView: View {
	var body: some View {
        NavigationView {
            ZStack {
                Color.yellow.ignoresSafeArea(.all, edges: .all)
                
                VStack {
                    Text("ContentView")
                        .padding()
                        .font(.title)
                        .foregroundColor(.white)
                }
            }
            .navigationTitle("Side Menu Demo")
            .navigationBarTitleDisplayMode(.inline)
            
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                        self.showMenu.toggle()
                    },
                    label: {
                        Image(systemName: "text.justify")
                            .font(.title3)
                            .foregroundColor(.red)
                    })
                }
            }
            .background(NavigationBarProxy(callback: { view, navBar in
            
                  print("""
                        navbar \(navBar.bounds)
                        view-inset \(view.safeAreaInsets)
                        """)
        	 }))
        }
     }
}

 

[결과]

navbar (0.0, 0.0, 390.0, 44.0)

view-inset UIEdgeInsets(top: 47.0, left: 0.0, bottom: 34.0, right: 0.0)

+ Recent posts