Create and hide UILabel

I created UILabel program code and clicked a button, I would like to hide the same shortcut. 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 } 

Did I miss something?

+4
source share
3 answers

This is another way to do the 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; } 
+2
source

In order for the button to be accessible from other methods, you need to assign it to an instance variable (directly or through a property), and not assign it to a local variable. The correct way to declare a property is

 @property(nonatomic, strong) UILabel *nameLabel; 

which can then be assigned for use

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

Later you can say

 self.nameLabel.hidden = YES; 

and it should work.

+2
source

It's hard to understand how this could be compiled, since the code that you show to create nameLabel makes it local to any method that is inside. Try to make the nameLabel property and use self.nameLabel whenever you refer to it, either by creating it or by touching its properties.

+1
source

Source: https://habr.com/ru/post/1447335/


All Articles