Ivan Kisin
Ivan Kisin

Reputation: 385

How to transfer variable from NSNumberFormatter to another ViewController?

I have a func with NSNumberFormatter:

@objc func doneClicked() {
                view.endEditing(true)


                let formatter = NumberFormatter()
                formatter.locale = Locale.current
                formatter.numberStyle = .decimal
                formatter.minimumSignificantDigits = 6

                if let text = textField.text, let number = formatter.number(from: text) {

                    year = number.doubleValue

                    mounthresult = year * 12

                    mounthLabel.text = formatter.string(from: NSDecimalNumber(value: year).multiplying(by: 12))

                }
    }

I need to process a data transfer to Label in another ViewController.

Making a prepare forSegue func:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "yearmounth" {
        let mounthController = segue.destination as! MounthsViewController

        mounthController.mounth = mounthresult
}

In this case transferred var haven't formatting. And shows without localization.

mounthresult = formatter.number(from: mounthLabel.text!) as! Double

This case gives nothing too... It's transferred but shows without formatter.

Also i tried to insert NumberFormatter to another controller's ViewDidLoad. But in this case NumberFormatter isn't load in ViewDidLoad...

Anyone knows the ways of solution?

Upvotes: 1

Views: 54

Answers (1)

Rafał Sroka
Rafał Sroka

Reputation: 40028

You could simply pass formatted text:

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "yearmounth" {
        let mounthController = segue.destination as! MounthsViewController

        mounthController.mounth = mounthLabel.text
   }

Or store the number in a variable and pass it similar way.

Upvotes: 1

Related Questions