Search code examples
swift2iboutlet

Accessing a content of an IBOutlet from another class


My question is simple , I have an IBoutlet(of a label) declared in a class , I need to change it content from another class , is that possible ? edit : The view of the IBoutlet is loaded in the other class through a scroll view

the first class :

var historyVariable = ""
class FirstViewController: UIViewController {
 override func viewDidLoad() {


    super.viewDidLoad()

 // here a code to set a value to historyVariable when button pressed

 Text().call()

   }
}

the second class

class  Text: UIViewController {

@IBOutlet var History: UILabel!
override   func viewDidLoad() {

    super.viewDidLoad()
   }
func call() {

History.text = "\(historyVariable)"
 }
}

it gives me an error unexpectedly found nil while unwrapping an Optional value when trying to set the text to the History label


Solution

  • Assuming text() is actually Text(), that would create a new, empty Text object. Since it's not part of the controller hierarchy, its view and other outlets aren't loaded at the time you invoke call().

    You either need to instantiate the Text controller from a storyboard (or otherwise) and present it so that it's properly initialized or else use one that's already active...if that's your intent.