Reputation: 4578
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!
Upvotes: 1
Views: 276
Reputation:
Tight coupling would be when a class like Sentence
, assumes a responsibility for something outside its concern, such as a view controller's outlet.
These types of changes can difficult to track down, as it is not obvious where the state was changed.
While you can loosely couple Sentence
by using delegation or notification, it would still make it more difficult, both for (unit or UI) testing, and for supporting and maintaining your code, when one class (in)directly affects the state of another class.
An alternate way
You can move this responsibility out of Sentence
by providing a public method for Sentence
which returns the desired property.
By establishing a clear interface boundary like this, it allows your code to be more modular, letting you make changes to either the implementation of Sentence, or to the view controller's outlets, without affecting something in the other class.
It also allows the view controller (from an MVC perspective) to be solely responsible for changing the view's text property.
Now, from the view controller, you can call a sentence instance's public method, then set the view controller's IBOutlet text property based on the returned value. This will make it obvious where and why the text has changed, instead of hiding that change in another (class's) method.
Upvotes: 3
Reputation: 42449
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:
Sentence
object.Sentence
instance that points back to the view controller, and have one of the protocol methods access the contents of the IBOutlet
.NSNotificationCenter
to fire a notification from your Sentence
object that your view controller is listening to, and can update its IBOutlet
directly.Upvotes: 5