2013-08-27 57 views
1

我从NSMutableArray动态创建标签。在创建标签时,我为每个标签设置了标签。我有一个NSMutableArray名为wordArray。现在,我想检查我的字符串是wordArray或不可用, 我可以检查这个使用:如何在iPhone中获取UILabel标签

[wordArray containsObject:wordStr]; 

用于动态创建标签:

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

使用上面的代码中,我创建标签和标签。 但是,如果wordArray包含字符串我想要更改该标签的textColor.I认为这可以使用标签来完成,但我怎样才能获得标签的标签值。

+0

你可以做的是存储这些标签在数组中标记,然后根据该标签获取标签。你可以轻松地做到我的朋友.... – NiravPatel

+0

你是否在'NSMutableArray'中存储了创建的'UILabels'?显示您的代码 –

+0

如果您提供代码,将有助于提供精确的解决方案 –

回答

0

我想你正在做类似的设置标签?

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

如果是这样,只是做:

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

好运。

+0

如果'yourView'具有多个具有相同标记的对象,该怎么办?哪一个返回?如果返回的视图不是'UILabel',那么你的代码如何处理? – Popeye

0

如果你想从它的标签获得UILabel。 你可以用下面的循环

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++; 
} 
1

对不起,我忽略了你的代码...你只需要添加要访问相应的标签下面几行:

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