1

I need to pass a variable from one ViewController to another and show the content of this variable in a textView. The following code computes correctly the number of words (in a very easy way) but it does not show it in the textView. Do someone know why is it not showing?:

EDIT: some new code added. Now it fails in the first VC, in the following line: DestViewController.num_words = num_words and it says: "use of unresolved identifier 'num_words'. If I make a global variable with any value, then it shows it in the textView without changing the content of the variable...

TransViewController

import UIKit
import Foundation

class TransViewController: UIViewController {

@IBOutlet var trad_text: UITextView!
@IBOutlet var buttonTrad: UIButton!
@IBOutlet var labelsitoh: UILabel!

@IBAction func butCalc(_ sender: UIButton) {

    let text = trad_text.text

    var num_words =  (text?.components(separatedBy: " ").count)!-1
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    var DestViewController : PaymentViewController = segue.destination as! PaymentViewController

    DestViewController.num_words =  num_words
}

override func viewDidLoad() {
    super.viewDidLoad()

    trad_text!.layer.borderWidth = 1
    trad_text!.layer.cornerRadius = 20
    trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

}

PViewControler

import UIKit
import Foundation

class PaymentViewController: UIViewController {

@IBOutlet var labelImport: UITextView!

var num_words = String()




override func viewDidLoad() {
    super.viewDidLoad()

    labelImport.text = num_words

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

Thank you so much for your time

alberzyzz
  • 277
  • 2
  • 15
  • Can you put a `print(Shared.shared.num_words)` before you of statement to check – Jimmy James Dec 09 '16 at 13:52
  • if I put it below the UITextView declaration, it says: "expected declaration" – alberzyzz Dec 09 '16 at 13:56
  • 3
    Why you have created Shared two times???? Show us how you are going from VC1 to VC2. – Vishal Sonawane Dec 09 '16 at 13:57
  • I go from VC1 to VC2 by control dragging a button – alberzyzz Dec 09 '16 at 13:59
  • 1
    `Shared` in `TransViewController ` is not same `Shared` from `PaymentViewController `. These are 2 different classes. Create a top level `Shared` class and try again. – Igor Bidiniuc Dec 09 '16 at 14:01
  • You have two different `Shared` classes, so the `Shared.shared.num_words` variable is different in each controller. Also, you should avoid the singleton pattern for this and pass data on the segue in the [`prepare(for: sender:)`](https://developer.apple.com/reference/uikit/uiviewcontroller/1621490-prepare) method in your view controller. – redent84 Dec 09 '16 at 15:21

0 Answers0