4

I created a UILabel programatically and triggering a button I would like to hide the same label. This is my code:

UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
nameLabel.text = @"TEXT";
nameLabel.backgroundColor = [UIColor greenColor];
nameLabel.numberOfLines = 5;
nameLabel.font = [UIFont boldSystemFontOfSize:12];
[self.view addSubview:nameLabel]; 

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Hide" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];    

- (IBAction)back{

  self.navigationItem.rightBarButtonItem=nil;

  [nameLabel setHidden: YES];  not working
   nameLabel.hidden = YES;     not working
}

Am I missing something?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Mitch1972
  • 69
  • 2
  • 9

3 Answers3

2

In order for the button to be accessible from other methods, you need to assign it to an instance variable (whether directly or via a property) rather than assigning it to a local variable. The proper way to declare the property is

@property(nonatomic, strong) UILabel *nameLabel;

which you can then assign to using

self.nameLabel = [[UILabel alloc] init...];

Later on, you can say

self.nameLabel.hidden = YES;

and it should work.

warrenm
  • 31,094
  • 6
  • 92
  • 116
2

This is also another way to do same

UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
nameLabel.text = @"TEXT";
nameLabel.tag = 1001;
nameLabel.backgroundColor = [UIColor greenColor];
nameLabel.numberOfLines = 5;
nameLabel.font = [UIFont boldSystemFontOfSize:12];
[self.view addSubview:nameLabel]; 

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Hide" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];    

- (IBAction)back{

  self.navigationItem.rightBarButtonItem=nil;
   UILabel *tempLabel = (UILabel *)[self.view viewWithTag:1001];
  [tempLabel setHidden: YES];  
   tempLabel.hidden = YES;     
}
rahul sharma
  • 111
  • 5
  • Thank you..I am quite new on programming. Could you explain me what is doing this line. nameLabel.tag = 1001; Thank you very much – Mitch1972 Nov 22 '12 at 00:47
  • This line give tag for this label. Tag is the identity of item in view. You can access items by their tag numbers. – rahul sharma Nov 22 '12 at 05:39
1

It's hard to know how that would even compile since the code you show to create nameLabel makes it local to whatever method that's in. Try making nameLabel a property and using self.nameLabel whenever you reference it, either creating it or touching its properties.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57