How to get a certain subview from UIView by tag

2019-03-14 09:38发布

问题:

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.

回答1:

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
            }
      }
}


回答2:

Example with UILabel:

UILabel *label = (UILabel *)[self.view viewWithTag:1];

good luck!



回答3:

You can get the subview with the code which others have mentioned, just like

UILabel *tagLabel = (UILabel*)[view viewWithTag:1];

But an important point to remember,

  • Make sure the parent view doesn't have the same tag value as of the subview. Otherwise the viewWithTag: method will return the receiver view (on which you are calling viewWithTag:) instead of returning the actual subview you want.

So keep the parent view and child views tags distinct whenever you need to use viewWithTag:.



回答4:

You could use the viewWithTag: method.



回答5:

Swift 3.0 and Swift 4.0

if let subLabel:UILabel = primaryView.viewWithTag(123) as? UILabel {
    subLabel.text = "do things here :-D"
}


回答6:

If you are on the same view

UILabel *tagLabel =  (UILabel*)[view viewWithTag:1];

Also, if you want a new instance of UILabel

UILabel *newTagLabel = [tagLabel copy];
//customize new label here...
[view addSubView:newTagLabel];