Search code examples
iosswiftuiviewcontrollernsobject

Swift: Transfer value from one class to another or to be specific from ViewController class to NSObject


How do I transfer a value from the viewDidLoad in a UIViewController to another class - NSObject.

Basically I have a MainViewController class and inside the class is a navigation bar. I wanted to access the height of the navigation bar and transfer the value to to another file/class which is -> class SettingsLauncher: NSObject.

Only way I can access the navigation Bar Height is inside viewDidLoad of the MainViewController class. This is might be the issue!

The SettingsLauncher needs to get the height value of the navigation Bar so it can display a small view right under the navigation bar.

From Code below:

The navBarHeight gets the height of the navigation bar. How can I transfer that value to my other class (SettingsLauncher)?

let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
let navBarHeight= self.navigationController?.navigationBar.frame.height ?? 0.0
let topBarHeight = statusBarHeight + navBarHeight

Solution

  • Create a struct in the MainViewController class, like so:

    class MainViewController: UIViewController {
    
        struct structure {
            static var topBarHeight = CGFloat()
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
            let navBarHeight= self.navigationController?.navigationBar.frame.height ?? 0.0
            structure.topBarHeight = statusBarHeight + navBarHeight
        }
    }
    

    Then use it to access the value from the SettingsLauncher object:

    class SettingsLauncher {
        var navHeight = MainViewController.structure.topBarHeight
    }