Friday, February 5, 2016

Objective C tagging views

We can tag views in Objective C using the UIView's tag property. Any object whose class is sub class of UIView class can be tagged like shown below.

[myView setTag:1234];

Let's say I have a view and it is having some sub views in it.

UIView *superView = [UIView alloc] init];

And I have some sub views added to it.

UIButton *subView1 = [UIButton alloc] init];
  [superView addSubView: subView1];

  UITextField *subView2 = [UITextField alloc] init];
  [superView addSubView: subView2];

  UILabel *subView3 = [UILabel alloc] init];
  [superView addSubView: subView3];

I have 3 sub views in my super view and to access these sub views fro my super view at run time, I have to go with below 

1. I need to make those subview objects (subView1, subView2, subView3) as global variables.



2. I need to write a loop to access sub views of my super view based on their class as shown below.

for(UIView v in superView.views){
    if([v isKindOfClass:[UILabel class]]){

    if([v isKindOfClass:[UITextField class]]){

    if([v isKindOfClass:[UIButton class]]){


Here, superView.views gives an array of all the views that are added to the super view. Though these 2 approaches solves our need, they are having some limitations and result in bad coding practice.

The first approach makes me to declare variables globally to access them and gives a bunch of global variables finally.

The second approach fails when there are more than one label or one button added to my superview.

We can avoid these approaches and the limitations they cause by using the tagging funda. Let's see how we can tag views to access them easily from their super view whenever we need them.

[subView1 setTag:111];
  [subView2 setTag:112];
  [subView3 setTag:113];

I have tagged sub views at the time of adding it to my super view as shown above.

Now I can access them as shown below using the viewWithTag method of UIView class.

for(UIView v in superView.views){

     UILabel *lbl     = [superView viewWithTag:113];

     UITextField *tf = [superView viewWithTag:112];

     UIButton *btn  = [superView viewWithTag:111];


Very simple and handy. Isn't it?


All you have to do is to remember the tags assigned to the views. :)

Here, even though I have bunch of same type of controls, my logic doesn't fail.

Hope this post is useful. Feel free to comment incase of any queries.