How to access an IBOutlet from another class How to access an IBOutlet from another class swift swift

How to access an IBOutlet from another class


@Sheen is correct about your immediate problem, but your problem is deeper. No object should access another object's IBOutlets. It's not well defined what will happen. This has been a long source of bugs in ObjC code, and Swift escalates those common bugs to crashes.

IBOutlets are not assigned until the view is loaded. This means that if the view controller is allocated but has not been put on the screen yet, the IBOutlets are still nil. Accessing an implicitly unwrapped nil will crash Swift.

View controllers should only communicate with their children view controllers. They should not communicate with arbitrary view controllers in the system. Communication between arbitrary view controllers is done via the model. One view controller updates the model, and another view controller reads from the model. This is the Model-View-Controller pattern that most of Cocoa is built around.

View controllers may interact more directly with their children, but still should not modify IBOutlets directly. They should set properties. It is the child view controller's responsibility to move that data from the property to the label at the correct time (which may have to wait until viewDidLoad()). That's why it's called the "view controller." It is the one object responsible for its views. No one else should mess with them.


Problem is here :

var lblred : UILabel! = UILabel()

You creating a new label here. That breaking your IBOutlet connection. You only need

@IBOutlet var lblred : UILabel!


Its not the recommended way to call a IBOutlet from another class. If u want to call or access a IBOutlet then you should set it as property and then access it.

For example:

//ViewControler.h#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UILabel *label;@end//abc.m#import <UIKit/UIKit.h>#import <ViewController.h>@interface abc@end@implementation abc- (void)viewDidLoad{[super viewDidLoad];ViewController *viewCOntroller= [ViewController alloc] init];viewCOntroller.label.text = @"Hello";}