1

I segue to a UIViewController, and during its init method, 2 labels' text is supposed to be specified. However, that doesn't happen and the text never changes. All the connections are right, but they aren't displaying anything, and I can't figure out why.

Below is the code that is supposed to change the UILabels for this particular ViewController.

-(id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        _nameLabel.text = @"NAME";
        _addressLabel.text = @"ADDRESS"; 
    }
    return self;
}

Below is the ".h" file for it:

@property (strong, nonatomic) Location *selectedLocation;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;

Any thoughts?

Vimzy
  • 1,871
  • 8
  • 30
  • 56

3 Answers3

1

in initWithCoder: the view is not loaded yet, which means that your outlets are still pointing to nil, even if the connections are correct.

The view is only constructed and outlets are connected when the first call to the view controller's view is made.

Consider doing this in viewDidLoad or viewWillAppear:.

Mohannad A. Hassan
  • 1,650
  • 1
  • 13
  • 24
1

I guess initWithCoder: is not called. It is recommended to set data you want in viewDidLoad.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.nameLabel.text = @"NAME";
    self.addressLabel.text = @"ADDRESS"; 
}

If not solved, check the views state, such as frame, hidden or alpha value.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"[nameLabel] frame : %@, hidden : %d, alpha : %@", NSStringFromRect(self.nameLabel.frame), self.nameLabel.hidden, self.nameLabel.alpha);
    NSLog(@"[addressLabel] frame : %@, hidden : %d, alpha : %@", NSStringFromRect(self.addressLabel.frame), self.addressLabel.hidden, self.addressLabel.alpha);
}

UPDATED: It's because of that IBOutlet is nil in the function initWithCoder:.

XIB-instantiated Object's IBOutlet is nil

Why isn't initWithCoder initializing items correctly?

Community
  • 1
  • 1
Joey
  • 2,912
  • 2
  • 27
  • 32
  • This did the trick, but why is it like this? I mean, when my object is initialized, I'm giving the proper details but it doesn't work? Also, why don't we have to reload the view after doing the same code in viewDidLoad? It all seems counter logical. – Vimzy May 12 '15 at 02:30
0

This is more of a style choice but you may want to synthesize your properties. You can do so using @synthesize myProperty; right above your init method(s) now you can set properties of objects like this: myLabel.text = @"Hello";

Depending on how you invoke this view controller, init may not always be called. try putting the text setting methods in viewDidLoad or even viewWillAppear (you will have to implement that last one)

Cole
  • 2,641
  • 1
  • 16
  • 34