Search code examples
objective-cuiviewuilabel

How to get a certain subview from UIView by tag


I'm a noob in Objective-C and I have one question.

I have one UILabel object that I adding to one UIView with this code:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,10,self.view.frame.size.width-15-70, 30)];
label.tag = 1;
label.font = [PublicObject fontTexts:17];
label.textAlignment = NSTextAlignmentRight;
label.textColor = [UIColor whiteColor];
[cell setBackgroundColor:[UIColor clearColor]];

 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
 view.backgroundColor = [PublicObject colorWithHexString:@"cd4110"];
 label.text = [filterData objectAtIndex:indexPath.row];
 view addSubview:label];

Now I want get one subview in my view where this subview has tag = 1 and save it on another object like this:

UILabel *tagLabel;
tagLabel = // I want get one subview in view where tag = 1 

Please help me understand how to do this.


Solution

  • You can get your subviews with for loop iteration

    for (UIView *i in self.view.subviews){
          if([i isKindOfClass:[UILabel class]]){
                UILabel *newLbl = (UILabel *)i;
                if(newLbl.tag == 1){
                    /// Write your code
                }
          }
    }
    

    Swift

    let label:UILabel = self.view.viewWithTag(1) as! UILabel