简体   繁体   中英

How to get UILabel Tags in iPhone

I am creating labels dynamically from NSMutableArray .While creating labels I have set tags for each label. I have one NSMutableArray named wordArray . Now, I want to check my string is available in wordArray or not, I can check this using :

[wordArray containsObject:wordStr];

For creating labels dynamically :

UILabel *wordLabl;
int tagValue3 = 1;
for (int iloop = 0; iloop < [wordArray count]; iloop++)
{

     wordLabl = [self addwordLabelRect:CGRectMake(80 * iloop + 20, 420 , 100,      20)andTag:tagValue3];//30 + 35 30 * iloop+
     [self.view addSubview:wordLabl];
     tagValue3 += 1;
}

-(UILabel *)addwordLabelRect:(CGRect)rect andTag:(int)integerValue
{
wordLabel = [[UILabel alloc] init];
wordLabel.frame = rect;
wordLabel.userInteractionEnabled = YES;
wordLabel.tag = integerValue;
wordLabel.backgroundColor = [UIColor clearColor];
wordLabel.font = [UIFont systemFontOfSize:15];
wordLabel.text = [NSString stringWithFormat:@"%@",[wordArray objectAtIndex:integerValue - 1]];
wordLabel.textAlignment = NSTextAlignmentCenter;
wordLabel.textColor = [UIColor whiteColor];

return wordLabel;
}

Using above code I am creating labels and Tags. But,If wordArray contains the string I want to change the textColor of that label.I think this can be done using Tag , but how can I get the tag value of the label.

Sorry, I overlooked you code... You just need to add following lines where you want to access your appropriate label:

if([wordArray containsObject:wordStr])
{
UILabel *label = (UILabel *) [self.view viewWithTag:([wordArray indexOfObject:wordStr] - 1)];//since u started tag assignment from 1
label.textcolor = [UIColor yellowColor];
}

I guess you're doing something like that to set the tags ?

for (NSUInteger i = 0; i < [wordArray count]; ++i) {
    UILabel * label;
    // setup your label...
    [label setTag:i];
    [yourView addSubview:label];
}

If so, just do :

NSUInteger index = [wordArray indexOfObject:wordStr];
if (index != NSNotFound) {
    UILabel * label = [yourView viewWithTag:index];
    // do whatever you want with your label
}

Good luck.

if you want to get UILabel from its Tag. you can use following loop

int i=0;
for (NSObject *view in self.View.subviews) 
{
    if ([view isKindOfClass:[UILabel class]]) 
    {
      label = (UILabel *)[[self view] viewWithTag:wordArray[i]];
        NSLog(@"%@",label.text);
       //here you get your label
    }
  i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM