xcode4.2 - Swift Accessing Viewcontrollers label from external class

170 views Asked by At

Where is the problem accessing a ViewController: UIViewController label (here: outlet called timerLabel)from AnotherClass. I would like to set a text.

class AnotherClass{

//[...]

 func updateTimeLabel(){
        // To Solve!!!*******
        //class name is ViewController?

    let myLabel = ViewController.timerLabel
    myLabel.text = "HiDuEi"
}

//[...]

// error message is:

//Instance member 'timerLabel' cannot be used on type 'ViewController'

}

how can I access the ViewController class (called ViewController) properly and access my outlet (a label) there, called timerLabel? THX

4

There are 4 answers

1
Adis On BEST ANSWER

ViewController is a type, not an instance of the object. You need to somehow get a reference to your ViewController instance and then access the label. E.g.

let viewController = ViewController()
viewController.timerLabel.text = "HiDuEi"

Note that this above creates a new instance, it's hard to say where your other viewController is created and how to access it from the code you posted.

1
Deepak Singh On

With the explanation of your question seems like, You have an IBOutlet (which can only be accessed with Instance) and you are trying to access it via Class (ViewController)

Create an object of ViewController and then try to update the text for timerLabel

let vc = ViewController()
vc.timerLabel.text = "HiDuEi"
0
Shehata Gamal On

You need to create a delegate for the class like

class ExternalClass{
   weak var delegate:VCName?
    func updateTimeLabel(){
    // To Solve!!!******* 
      delegate?.timerLabel.text = "HiDuEi" 
    }
 }

When create

 let ca = ExternalClass()
 ca.delegate = self
0
developing2020 On

You could assign an identifier to the view controller you are trying to access the label from, instantiate it, then access the label, like so:

var vc : ViewController = storyboard.instantiateViewControllerWithIdentifier("abc") as! ViewController
vc.timerLabel.text = "HiDuEi"

where "abc" is the identifier you used