Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 440
user3797431 Avatar asked Jul 02 '14 11:07

user3797431


People also ask

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.

What is a tag in Swift?

An integer that you can use to identify view objects in your application.


2 Answers

Example with UILabel:

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

good luck!

like image 64
or azran Avatar answered Oct 10 '22 09:10

or azran


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 
like image 30
Hiren Avatar answered Oct 10 '22 08:10

Hiren