Nisar Ahmad
Nisar Ahmad

Reputation: 937

How to access UILabel created programmatically without tag?

I am new to iOS development, working on an iPad app, having XIBs with a lot of UI elements, so I want to create them programmatically and get data from these Labels and TextFields. So how to access these fields without using tags, is there any way to access them ?

Upvotes: 1

Views: 846

Answers (4)

Munahil
Munahil

Reputation: 2419

In your .h file, make IBOutlet like this :

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

In your nib or storyboard. Right click your View Controller. You will get a list, select "lbl" (in this case) from your Outlet and drag it to the "lbl" and connect. You can now access this label by writing self.lbl anywhere in your View Controller

Upvotes: 0

CatVsDogs
CatVsDogs

Reputation: 374

This code gets all the labels in a view controller, If you want to find all the text fields replace UILabel with UITextfield

UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
[lbl setText:@"Hello World"];
[self.view addSubview:lbl];
for(id x in [self.view subviews])
{
    if([x isMemberOfClass:[UILabel class]])
    {
        NSLog(@"%@",x);
    }
}

Upvotes: 2

Pravin Tate
Pravin Tate

Reputation: 1130

declare it in .h file as like follow

UILabel * userName;

and access it in .m file directly with using of it's name (userName) no need for Tag here i.e.

NSLog(@"userName %@",userName);

Upvotes: 0

Pepeng Hapon
Pepeng Hapon

Reputation: 367

I don't know what you want to do but here,

You can get the properties and/or values of Labels or TextFields by these:

for(UILabel *lbl in self.view.subviews) {
    // get labels properties here
    NSLog(@"Label : %@", lbl.text);

}

for(UITextField *tf in self.view.subviews) {
    // get the textfield properties here
    NSLog(@"TextField : %@", tf.text);
}

Upvotes: 0

Related Questions