Search code examples
iosswiftuilabeliboutlet

How to set @IBOutlet text from a Class method


I have a class called Sentence and I would like to set the text property of my @IBOutlet in my ViewController in one of the methods of Sentence. Is that possible? If not, within the Sentence class method itself, how can I make a call or a function which sets my @IBOutlet text from the class method?

Here is my UILabel

@IBOutlet weak var kleinGrossLabel: UILabel!


Solution

  • You can't assign an IBOutlet from a UIViewController in a class method of another class. How is that other class (in your case Sentence) supposed to know about the view controller?

    You have a few options:

    1. Keep a reference to your view controller in your Sentence object.
    2. Use delegation: set a delegate on your Sentence instance that points back to the view controller, and have one of the protocol methods access the contents of the IBOutlet.
    3. Use NSNotificationCenter to fire a notification from your Sentence object that your view controller is listening to, and can update its IBOutlet directly.